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

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

我是 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) returns [][]interface {},

reflect.TypeOf(resp.Values[0])(即column)returns []interface {},

reflect.TypeOf(resp.Values[0][0])(即 word)returns string.

我的最终目标是让每个单词都有自己的数组,所以不用:

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

确保值具有某种类型的规定方法是使用 type assertion,它有两种形式:

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 -> %#v\n", word)
  continue
}
s[0] = str