我想知道调用具有多个返回值的函数的正确语法是什么,其中一个(或多个)类型为 interface{}
。
返回 interface{}
的函数可以这样调用:
foobar, ok := myfunc().(string)
if ok { fmt.Println(foobar) }
但以下代码失败并出现错误 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
}
}
那么,正确的调用约定是什么?
最佳答案
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")
}
}
您只能申请 type assertion到单个表达式。
关于interface - 具有接口(interface){}和类型断言的多个返回类型(在 Go 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7045848/