抱歉這個基本問題。我是 GoLang 的新手。我有一個名為的自定義類型ProtectedCustomType,我不希望其中的變量set直接由調用者使用,而是希望一個Getter/Setter方法來執行此操作下面是我的ProtectedCustomTypepackage customtype ProtectedCustomType struct { name string age int phoneNumber int}func SetAge (pct *ProtectedCustomType, age int) { pct.age=age} 這是我的main功能import ( "fmt" "./custom")var print =fmt.Printlnfunc structCheck2() { pct := ProtectedCustomType{} custom.SetAge(pct,23) print (pct.Name)}func main() { //structCheck() structCheck2()}但是我無法繼續進行.. 你能幫我看看如何在 GoLang 中實現 getter-setter 概念嗎?
1 回答

慕斯王
TA貢獻1864條經驗 獲得超2個贊
如果你想有 setter 你應該使用方法聲明:
func(pct?*ProtectedCustomType)?SetAge?(age?int)??{ ????pct.age?=?age }
然后你就可以使用:
pct.SetAge(23)
這種聲明使您能夠通過使用
(pct *ProtectedCustomType)
您正在將指針傳遞給您的結構,因此對它的操作會改變其內部表示。
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消