【问题标题】:Multiple return types with interface{} and type assertions (in Go)具有 interface{} 和类型断言的多种返回类型(在 Go 中)
【发布时间】:2011-10-26 03:03:53
【问题描述】:

我想知道调用具有多个返回值的函数的正确语法是什么,其中一个(或多个)是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
    }
}

那么,正确的调用约定是什么?

【问题讨论】:

    标签: interface go


    【解决方案1】:
    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 应用于单个表达式。

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 2017-07-31
      • 1970-01-01
      • 2014-01-12
      • 2016-12-13
      • 1970-01-01
      相关资源
      最近更新 更多