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

3
  • 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). Commented Jan 19, 2018 at 17:11
  • 1
    ... more here and here. Commented Jan 19, 2018 at 17:15
  • 1
    Have a look if this helps you: stackoverflow.com/a/71930507/18579038 Commented Apr 19, 2022 at 19:56

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.