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

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

概述假设我有这个: type Donut stringtype Muffin stringfunc getPastry () (interface{}, error) { // some logic - this is contrived var d Donut d = "Bavarian" return d, nil} 是否可以将其减少到一行: p, err := getPa 假设我有这个:

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)

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

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

总结

以上是内存溢出为你收集整理的Golang:你能在一个语句中输入一个返回的接口{}吗?全部内容,希望文章能够帮你解决Golang:你能在一个语句中输入一个返回的接口{}吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1267734.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存