Multiple return types with interface {} and type statements (in Go)

I am wondering what the correct syntax is for function calls with multiple return values, one (or more) of which is of type interface{}.

A function that returns interface{}can be called as follows:

foobar, ok := myfunc().(string)
if ok { fmt.Println(foobar) }

but the following code failed multiple-value foobar() in single-value context:

func foobar()(interface{}, string) {
    return "foo", "bar"
}


func main() {
    a, b, ok := foobar().(string)
    if ok {
        fmt.Printf(a + " " + b + "\n") // This line fails
    }
}

So what is the correct calling convention?

+5
source share
1 answer
package main

import "fmt"

func foobar() (interface{}, string) {
    return "foo", "bar"
}

func main() {
    a, b := foobar()
    if a, ok := a.(string); ok {
        fmt.Printf(a + " " + b + "\n")
    }
}

You can only apply a type statement to a single expression.

+5
source

All Articles