-1

I have an interface that has some strings. I want to print each item one by one. For example, consider the following interface.Here I want to print sud first then man

var x interface{} = []string{"sud", "man"}
randomDev
  • 73
  • 9
  • 3
    Use the `for` statement. You can use it with the `range` clause or just the traditional init-cond-post form. https://go.dev/ref/spec#For_statements. And when the slice is stored in an interface value, then you first need to **type-assert** the value to the correct slice type, for more on assertions, read: https://go.dev/ref/spec#Type_assertions. Alternatively you could also use reflection when you do not know the concrete type upfront. – mkopriva Jan 01 '23 at 08:31
  • @mkopriva thanks for responding. I am not able to loop through x. I am getting an error **cannot range over x (variable of type interface{})** – randomDev Jan 01 '23 at 08:44
  • 5
    Take the Tour of Go to learn the language basics. – Volker Jan 01 '23 at 10:19

1 Answers1

3

You can use something like this:

    var x interface{} = []string{"sud", "man"}

    res, ok := x.([]string)
    if !ok {
        fmt.Errorf("error")
    }

    for i := range res {
        fmt.Println(res[i])
    }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83