Golang: Can you enter the return interface {} in a single expression?

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 that does not compile:

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

It’s not that having two lines of code to get a “generic” and a type is a big deal, but for me it’s just wasteful and not easy, and that usually means I miss something obvious :-)

+4
source share
2 answers

You can not. The best you can do is write a helper function (and make a type statement in it):

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

And then it becomes single-line:

d, err := getDonut(getPastry())

Or you can even “include” the call getPastry()in a helper function:

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

( ):

d, err := getDonutPastry()

:

, , getPastry(), Donut, . , :

v, ok := x.(T)

. ok true, . false, v - T. .

( , ):

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!")
    }
}

. :

, "ok" ,

Go:

+7

: .

:
, , .

, , .. , , :

thisPastry, err := getPastry()
if err != nil { ... }

switch v := thisPastry.(type) {
case Donut:
    fmt.Println(v)
case Muffin:
    fmt.Println(v, "mmm!")
default:
    // some kind of error?
}
+4

Source: https://habr.com/ru/post/1651418/


All Articles