使用interface{}和类型断言实现多个返回类型(在Go中)

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2011年8月13日 04:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/7045848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定