如何使用其他结构变量访问不同的结构变量?

我有两个结构,一个包含一个字段,另一个包含三个字段:-


type User struct {

  Name []CustomerDetails `json:"name" bson:"name"`

}

type CustomerDetails struct {

  Value             string `json:"value" bson:"value"`

  Note              string `json:"note" bson:"note"`

  SendNotifications bool   `json:"send_notifications" bson:"send_notifications"`

}

CustomerDetails我想使用User结构字段访问字段


func main() {

  var custName User

  custName.Name.Value = "ABC"

  fmt.Println(custName)

}

但它给了我错误


custName.Name.Value 未定义(类型 []CustomerDetails 没有字段或方法值)


游乐场链接

我将如何解决这个错误?谁能帮我?



海绵宝宝撒
浏览 107回答 2
2回答

湖上湖

type User struct {  Name []CustomerDetails `json:"name" bson:"name"`}在这里,User.Name是 slice,这就是你出错的原因。func main() {  var custName User  custName.Name = append(custName.Name, CustomerDetails{    Value: "ABC",  })  fmt.Println(custName)}https://play.golang.org/p/J56LjH7Lqdd

肥皂起泡泡

CustomerDetails您应该像User.Name这样附加: https://play.golang.org/p/jk73roZiAC2var custName Usercd := CustomerDetails{        Value: "ABC",        Note: "Test",    }custName.Name = append(custName.Name, cd)fmt.Println(custName)User.Name是一个切片,所以你不能给它一个单一的值。
打开App,查看更多内容
随时随地看视频慕课网APP