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

Naj*_*aji 0 arrays types interface go type-assertion

我是 Go 新手,由于某种原因我所做的事情对我来说似乎不太直接。

这是我的代码:

for _, column := range resp.Values {
  for _, word := range column {

    s := make([]string, 1)
    s[0] = word
    fmt.Print(s, "\n")
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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]]]

mae*_*ics 6

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

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

你的代码可能应该做这样的事情:

str, ok := word.(string)
if !ok {
  fmt.Printf("ERROR: not a string -> %#v\n", word)
  continue
}
s[0] = str
Run Code Online (Sandbox Code Playgroud)