douyalin0847 2018-01-19 17:04
浏览 191
已采纳

无法在分配中将单词(类型接口{})用作类型字符串:需要类型声明

I'm new to Go and what i'm doing for some reason doesn't seem very straight-forward to me.

Here is my code:

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

    s := make([]string, 1)
    s[0] = word
    fmt.Print(s, "
")
  }
}

and I get the error:

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

resp.Values is an array of arrays, all of which are populated with strings.

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

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

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

My end goal here is to make each word its own array, so instead of having:

[[Hello, Stack], [Overflow, Team]], I would have: [[[Hello], [Stack]], [[Overflow], [Team]]]

  • 写回答

1条回答 默认 最新

  • doudeng5218 2018-01-19 17:58
    关注

    The prescribed way to ensure that a value has some type is to use a type assertion, which has two flavors:

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

    Your code should probably do something like this:

    str, ok := word.(string)
    if !ok {
      fmt.Printf("ERROR: not a string -> %#v
    ", word)
      continue
    }
    s[0] = str
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大