英文:
Multiple return types with interface{} and type assertions (in Go)
问题
我想知道调用具有多个返回值的函数的正确语法,其中一个(或多个)返回值的类型是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") // 这一行出错
}
}
那么,正确的调用约定是什么?
英文:
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?
答案1
得分: 5
你只能对单个表达式应用类型断言。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论