开发者

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

I'm wondering what the correct syntax is for calling functions with multiple return values, one (or more) of which is of type interface{}.

A function which returns interface{} can be called like this:

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

but the following code fails with the error 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?


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 assertion to a single expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜