Search code examples
goredigo

Convert interface{} into []string in Golang


I am new to GO language and I am trying to get a value from a function which returns two strings, that is [str1, str2]

 ret, err := fun1(....)

And function's prototype is

func fun1(...) (interface{}, error)

I print ret, it is

[[57 57 56 56] [97 100 98 49 57 55 102 98 49 101 57 48 52 98 102 56 55 102 52 56 57 57 55 54 49 55 101 57 49 100 98 49]]

which looks like the type [][]uint8, so, I tried this way

    v, _ := ret.([][]uint8)
    str1, _ := strconv.Atoi(string(v[0]))
    str2, _ := strconv.Atoi(string(v[1]))

it failed, v is []

And I also tried:

   v, _ := ret.([]string)

nothing changed

How to solve this? Any help will be appreciated :)

PS: I debug and find the first string is "9988"


Solution

  • The value ret is an []interface{} containing []byte elements. Use the following code to convert to a slice of strings:

    // Use type assertion to get []interface from ret
    sitf, ok := ret.([]interface{})
    if !ok { /* handle unexpected type here */ }
    
    // Create the result slice.
    s := make([]string, len(sitf))
    
    // For each element …
    for i := range sitf {
        // Use type assertion to get []byte from interface{}
        sbyte, ok := sitf[i].([]byte)
        if !ok { /* handle unexpected type here */ }
    
        // Convert the []byte to a string and set in result
        s[i] = string(sbyte)
    }
    

    I know from your other questions that you are asking about Redigo. You can use the redis.Strings helper function instead of the code above:

    s, err := redis.Strings(fun1(....))
    

    The variabile s is a []string.

    See the documentation about reply helpers for more information.