2016-06-10 14:50
浏览 287


Problem in Playground: https://play.golang.org/p/UKB8f4qGsM

I have a slice of interfaces, I know for sure which type they have (in reality i don't so I'd have to type switch it, but I left that out for clarity). How can I assign a value to a field in the struct behind the interface? The type assertion seems to take away the reference.

I also tried using pointers, that too doesn't work though, mostly because I can't type assert then (type *inter cannot be type asserted) and when I dereference it, it kinda makes it pointless to even have...

I'm not that experienced in Go, I would appreciate every help I can get.

图片转代码服务由CSDN问答提供 功能建议

游乐场中的问题: https://play.golang.org/p/UKB8f4qGsM

我有一部分接口,我确定它们具有哪种类型(在 现实我不是,所以我必须键入switch,但是为了清楚起见,我省略了它。 如何为接口后面的结构中的字段分配值? 类型断言似乎夺走了引用。

我也尝试过使用指针,但这也行不通,主要是因为我当时不能键入断言(类型* inter不能为 类型断言),而当我取消引用它时,甚至还没有意义……

我对Go并不了解,我将不胜感激。 / p>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douao8204 2016-06-10 14:53

    You can't change the value stored in the interface, you need to use a pointer to the value you want to change:

    for i := 0; i < 5; i++ {
        slice = append(slice, &b{a: a{name: "Tom"}})
    for i, _ := range slice {
        x := slice[i].(*b)
        x.name = "Tim"
    解决 无用
    打赏 举报

相关推荐 更多相似问题