最后,這個問題肯定要看個人喜好了。盡管如此,我還是想大膽嘗試找出哪種風格是首選。我最近注意到我的代碼中存在不一致之處。我有一個包含一些字段的結構?,F在的問題是當我需要調用一個函數來獲取我想要設置的值時,編輯這個字段的慣用方法是什么。我是在函數內部設置值,還是返回它并在我的調用函數中設置它?type SuperStruct struct { OneValue string AnotherValue string}func (s *SuperStruct) makeAnotherValue() { s.AnotherValue = "Hello there"}func main() { superStruct := SuperStruct{} superStruct.makeAnotherValue()}或(具有相同的結構)func (s *SuperStruct) makeAnotherValue() string { return "Hello there"}func main() { superStruct := SuperStruct{} superStruct.AnotherValue = superStruct.makeAnotherValue()}我知道在某些情況下,這些方法中只有一種是有意義的。但我經常發現自己處于兩者皆有可能的境地。我想第二種方式可以提供更好的保護,但有時這不是問題。
1 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
我認為慣用的方法是完全刪除您的功能:
func main() {
superStruct := SuperStruct{AnotherValue:"Hello there"}
}
或者
func main() {
superStruct := SuperStruct{}
...
superStruct.AnotherValue = "Hello there"
}
除非絕對必要,否則不要構建 getters/setters/create 函數,只做需要的工作。如果你只是設置一個簡單的字段,在大多數情況下你不需要工廠來制作字段值。如果您認為該函數是必要的,它需要比這復雜得多(至少幾行)并且通常被稱為 NewAnotherValue 并且不附加到父結構。
通過另一個函數/結構的每個間接訪問都會使代碼更難理解。
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消