【问题标题】:Cannot use word (type interface {}) as type string in assignment: need type assertion不能在赋值中使用 word (type interface {}) 作为类型字符串:需要类型断言
【发布时间】:2018-06-28 23:46:39
【问题描述】:

我是 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[0] = word.(string)
  • ...更多herehere

标签: arrays go types interface type-assertion


【解决方案1】:

确保值具有某种类型的规定方法是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2012-12-26
    • 1970-01-01
    • 2015-07-23
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多