具有接口{}和类型断言的多种返回类型(在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 + "
") // This line fails
}
}
So, what is the correct calling convention?
我想知道调用具有多个返回值(其中一个(或多个))的函数的正确语法是什么 的类型为 返回 以下代码失败,并在单值上下文中出现错误 那么,正确的调用约定是什么? p>
div> interface {} code>。 p>
interface {} code>的函数可以这样调用: p> \ n
foobar,好的:= myfunc()。(字符串)
if好的{fmt.Println(foobar)}
code> pre>
multi-value foobar() code>: p>
func foobar()(interface {},字符串 ){
return“ foo”,“ bar”
}
func main(){
a,b,ok:= foobar()。(string)
if OK {
fmt.Printf (a +“” + b +“
”)//此行失败
}
}
code> pre>
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 + "
")
}
}
You can only apply a type assertion to a single expression.