不能在赋值中使用单词(类型接口 {})作为类型字符串:需要类型断言



我是Go的新手,由于某种原因我正在做的事情对我来说似乎不是很简单。

这是我的代码:

for _, column := range resp.Values {
  for _, word := range column {
    s := make([]string, 1)
    s[0] = word
    fmt.Print(s, "n")
  }
}

我收到错误:

Cannot use word (type interface {}) as type string in assignment: need type assertion

resp.Values是一个数组数组,所有这些数组都填充了字符串。

reflect.TypeOf(resp.Values)返回[][]interface {}

reflect.TypeOf(resp.Values[0])(column(返回[]interface {}

reflect.TypeOf(resp.Values[0][0])(word(返回string

我在这里的最终目标是使每个单词成为自己的数组,因此而不是:

[[Hello, Stack], [Overflow, Team]],我会: [[[Hello], [Stack]], [[Overflow], [Team]]]

确保值具有某种类型的规定方法是使用类型断言,它有两种风格:

s := x.(string) // panics if "x" is not really a string.
s, ok := x.(string) // the "ok" boolean will flag success.

您的代码可能应该执行以下操作:

str, ok := word.(string)
if !ok {
  fmt.Printf("ERROR: not a string -> %#vn", word)
  continue
}
s[0] = str

相关内容

最新更新