arrays - 不能在赋值 : need type assertion 中使用字(类型接口(interface) {})作为类型字符串

标签 arrays go types interface type-assertion

我是 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/

相关文章:

java - 单独存储 YEAR 的包装数据类型

java - 是否可以声明 String[][] 类型的全局数组?

c++ - 用数组重载运算符 += C++

ios - 如何组织tableview单元格

ubuntu - 在 ubuntu 上使用官方存档安装 go-vim 后无法正常工作

amazon-web-services - 使用 Go 设置 AWS Lambda,为什么我总是用这个简单的函数得到 "Internal server error"?

types - Ocaml - 多态打印和类型丢失

arrays - 在 Swift 中读取 plist 文件的内容

oop - Go:接口(interface)中的可选方法

java - Java中具有不同引用类型的对象类型有什么优点?