简体   繁体   中英

GoLang - Generics instead of interface to return different types

I read a lot of docs but I couldn't find if I'm able to do it.

Is there a way to do something like this in Go without use an interface as return type?

Playground example

package main

import "fmt"

type Foo struct {
    Id uint
    FooField string
}

type Bar struct {
    Id uint
    BarField string
}

type Model interface {
    Foo | Bar
}

func build[T Model](s string) T {
    if s == "foo" {
        fmt.Println(s)
        return Foo{}
    }
    fmt.Println(s)
    return Bar{}
}

func main() {
    build("foo")
}

No, at least not how you've shown here.

Go is a statically typed language, meaning that the semantic data types of values do not depend on any dynamic values in the program.

Interfaces are not an exception to this, but an extension . From the language specification (abridged):

The static type (or just type) of a variable is the type given in its declaration. Variables of interface type also have a distinct dynamic type, which is the (non-interface) type of the value assigned to the variable at run time.

Here's an alternate version that would work.

func build[T Model]() T {
    var x T
    return x
}

func main() {
    //    VVV explicitly passing the type parameter, not a string
    build[Foo]()
}

The reason why this is valid and yours isn't, is because now the return type only depends on the type parameter provided, which is always static. Type parameters are often omitted entirely when they can be inferred by the compiler, but in cases like this, it's most correct to list them explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM