2018-01-19 17:04
浏览 106


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]]]

图片转代码服务由CSDN问答提供 功能建议

我是Go的新手,出于某种原因,我正在做的事情似乎并不直接 我。


对于_,单词:  =范围列{
s:= make([] string,1)
s [0] = word 


不能在分配中使用word(类型接口{})作为类型字符串:需要类型断言< / code>

resp.Values 是一个数组数组,所有数组均填充有字符串。

< code> reflect.TypeOf(resp.Values)返回 [] []接口{}

reflect.TypeOf(resp。 值[0])(它是)返回 [] interface {}

reflect .TypeOf(resp.Values [0] [0])(即 word )返回 string


[[Hello,Stack],[Overflow,Team]] ,我将拥有: [[[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)
    s[0] = str
    打赏 评论

相关推荐 更多相似问题