Search code examples
gogo-interface

In golang how to loop through string interface


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"}

Solution

  • 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])
        }