Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

interface

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?

like image 588
snim2 Avatar asked Aug 12 '11 20:08

snim2


1 Answers

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.

like image 119
peterSO Avatar answered Sep 30 '22 04:09

peterSO