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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别