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条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示