我正在尝试在用户结构中创建数组后使用 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 关注
- 88 浏览
添加回答
举报
0/150
提交
取消