Search code examples
arraysgotypesinterfacetype-assertion

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


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, "\n")
  }
}

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


Solution

  • 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\n", word)
      continue
    }
    s[0] = str