0

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

Naji
  • 674
  • 2
  • 14
  • 35
  • 5
    You need to first type assert that the word is actually a string. One, prone-to-panic, way would be `s[0] = word.(string)`. – mkopriva Jan 19 '18 at 17:11
  • 1
    ... more [here](https://tour.golang.org/methods/15) and [here](https://golang.org/ref/spec#Type_assertions). – mkopriva Jan 19 '18 at 17:15
  • 1
    Have a look if this helps you: https://stackoverflow.com/a/71930507/18579038 – Arsham Arya Apr 19 '22 at 19:56

1 Answers1

5

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
maerics
  • 151,642
  • 46
  • 269
  • 291