我是 Go 的新手,出于某种原因我正在做的事情对我来说似乎不是很直接。
这是我的代码:
for _, column := range resp.Values {
for _, word := range column {
s := make([]string, 1)
s[0] = word
fmt.Print(s, "\n")
}
}
我得到了错误:
不能在赋值中使用 word (type interface {}) 作为类型字符串:需要类型断言
resp.Values
是一个数组数组,所有数组都填充有字符串。
reflect.TypeOf(resp.Values)
返回 [][]interface {}
,
reflect.TypeOf(resp.Values[0])
(即列
)返回[]interface {}
,
reflect.TypeOf(resp.Values[0][0])
(即 word
)返回 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
关于arrays - 不能在赋值 : need type assertion 中使用字(类型接口(interface) {})作为类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346116/