加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang:你能在一个语句中输入一个返回的接口{}吗?

发布时间:2020-12-16 09:28:19 所属栏目:大数据 来源:网络整理
导读:假设我有这个: type Donut stringtype Muffin stringfunc getPastry () (interface{},error) { // some logic - this is contrived var d Donut d = "Bavarian" return d,nil} 是否可以将其减少到一行: p,err := getPastry()thisPastry := p.(Donut) 换句
假设我有这个:

type Donut string
type Muffin string

func getPastry () (interface{},error) {
  // some logic - this is contrived
  var d Donut
  d = "Bavarian"
  return d,nil
}

是否可以将其减少到一行:

p,err := getPastry()
thisPastry := p.(Donut)

换句话说,这样的东西,不编译:

thisPastry,err := getPastry().(Donut,error)

不是有两行代码来获得“通用”并输入它是一件大事,但它对我来说只是感觉浪费和不简单,这通常意味着我错过了一些明显的东西:-)

解决方法

你不能.你能做的最好就是编写一个辅助函数(并在其中执行类型断言):

func getDonut(p interface{},err error) (Donut,error) {
    return p.(Donut),err
}

然后它变成了一条线:

d,err := getDonut(getPastry())

或者你甚至可以在helper函数中“合并”getPastry()调用:

func getDonutPastry() (Donut,error) {
    p,err := getPastry()
    return p.(Donut),err
}

然后调用它(更短的单行):

d,err := getDonutPastry()

注意:

当然,如果getPastry()返回的值不是动态类型Donut,那么这将是运行时恐慌.为防止这种情况,您可以使用type assertion的特殊形式:

v,ok := x.(T)

这会产生额外的无类型布尔值.如果断言成立,则ok的值为true.否则为false,v的值为类型T的零值.在这种情况下,不会发生运行时混乱.

使用特殊形式的辅助函数的安全版本可能看起来像这样(它们返回错误而不是恐慌):

func getDonut2(p interface{},error) {
    if d,ok := p.(Donut); ok {
        return d,err
    } else {
        return "",errors.New("Not a Donut!")
    }
}

func getDonutPastry2() (Donut,err := getPastry()
    if d,errors.New("Not a Donut!")
    }
}

查看相关问题:

Return map like ‘ok’ in Golang on normal functions

Go: multiple value in single-value context

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读