我正在嘗試在用戶結構中創建數組后使用 SetAge() 函數更新數據結構的“年齡”。這是代碼片段://data struct to set the user detailstype data struct { Name string `json:"name"` College string `json:"college"` Age int64 `json:"age"`}// user struct to store the user details in JSON Array type user struct { DataValue []*data `json:"data"`}func (u *user) Details(name, college string) *user { d:=&data{Name:name, College:college} u.DataValue=append(u.DataValue, d) return u}func (u *user) SetAge(age int64) *user { //age is optional // what code should be here such that age is added to resp detail}Output:"data":[{ "name":"test", "college":"test", "age":10},{ "name":"test", "college":"test" // in this object "Age" hasn't been set}]
2 回答

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
如果你想更新所有對象的字段,你Age就差不多完成了。data
您只需要遍歷u.DataValue切片,并按如下方式更新年齡字段:
func (u *user) SetAge(age int64) *user {
for index := range u.DataValue {
u.DataValue[index].Age = age
}
return u
}

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
根據我的應用程序的要求,它會是這樣的:
func (u *user) SetAge(age int64) *user {
u.DataValue[len(u.DataValue) - 1].Age = age
return u
}
- 2 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消