donglian2106 2017-03-11 20:46
浏览 127
已采纳

将接口{}转换为字符串数组

I'm trying to get the data which is stored in interface[] back to string array. Encountering an unexpected error.

type Foo struct {
    Data interface{}
}

func (foo Foo) GetData() interface{} {
    return foo.Data
}

func (foo *Foo) SetData(data interface{}) {
    foo.Data = data
}

func main() {
    f := &Foo{}
    f.SetData( []string{"a", "b", "c"} )

    var data []string = ([]string) f.GetData()
    fmt.Println(data)
}

Error: main.go:23: syntax error: unexpected f at end of statement

Go Playground

  • 写回答

1条回答 默认 最新

  • douyuan4697 2017-03-11 20:46
    关注

    What you are trying to perform is a conversion. There are specific rules for type conversions, all of which can be seen in the previous link. In short, you cannot convert an interface{} value to a []string.

    What you must do instead is a type assertion, which is a mechanism that allows you to (attempt to) "convert" an interface type to another type:

    var data []string = f.GetData().([]string)
    

    https://play.golang.org/p/FRhJGPgD2z

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line