dsdsds12222 2016-08-16 14:12
浏览 20
已采纳

Golang:您能否在一个语句中键入返回的接口{}?

Let's say I have this:

type Donut string
type Muffin string

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

Is it possible to reduce this to one line:

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

In other words, something like this, which does not compile:

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

Not that having two lines of code to get the "generic" and type it is a big deal, but it just feels wasteful and un-simple to me, and that usually means I'm missing something obvious :-)

  • 写回答

2条回答 默认 最新

  • duanmei4362 2016-08-16 14:22
    关注

    You can't. Best you can do is write a helper function (and do the type assertion in that):

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

    And then it becomes a one-line:

    d, err := getDonut(getPastry())
    

    Or you may even "incorporate" the getPastry() call in the helper function:

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

    And then calling it (an even shorter one-liner):

    d, err := getDonutPastry()
    

    Note:

    Of course if the value returned by getPastry() is not of dynamic type Donut, this will be a runtime panic. To prevent that, you may use the special form of the type assertion:

    v, ok := x.(T)
    

    Which yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case.

    Safe versions of the helper functions using the special form could look like this (they return an error rather than panic):

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

    See related questions:

    Return map like 'ok' in Golang on normal functions

    Go: multiple value in single-value context

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题