我想知道调用具有多个返回值的函数的正确语法是什么,其中一个(或多个)返回值的类型为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
}
}那么,正确的调用约定是什么呢?
发布于 2011-08-13 05:36:13
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应用于单个表达式。
https://stackoverflow.com/questions/7045848
复制相似问题