Home > database >  Return the struct instead of an instance of it in Go?
Return the struct instead of an instance of it in Go?

Time:08-30

Is there any way I can do to return struct instead of its instance? For example, I have a Car Interface that can return the struct of its tire.

type Car interface {
    GetTireType()
}

type RaceCar struct {}
type RaceTire struct {}

func (car RaceCar) GetTireType() {
    return RaceTire
}

Is that in some way achievable in Go? Thank you.

CodePudding user response:

I think your problem is more related to object oriented concepts than Golang, however I might be wrong.

Here is an implementation that models what I understand of your problem:

type Car interface {
    GetTireType() TireType
}

type TireType int

const (
    RaceTireType TireType = iota
    StreetTireType
)

type Tire struct {
    Type TireType
}

// these are optional, see the comment inside GetTireType()
var (
    RaceTire  Tire = Tire{RaceTireType}
    StreeTire Tire = Tire{StreetTireType}
)

type RaceCar struct{}
type StreetCar struct{}

func (car RaceCar) GetTireType() Tire {
    // Here you could also directly return Tire{RaceTireType}
    return RaceTire
}

func (car StreetCar) GetTireType() Tire {
    return StreeTire
}

I think the main confusion in your code is that RaceTire is a specialized type of tire, so it should not be a struct. The Tire is the struct with all the properties (like a Class). Then RaceTire and StreetTire all have the same properties, only different values (like an Object).

CodePudding user response:

No. Because GetTireType() can return only one type of struct. What you can do is, return an interface. So you can use type switch to compare the concrete type of that interface against multiple types specified in various case statements.

type Car interface {
    GetTireType() Tire
}

type Tire interface {
}

type RaceCar struct{}
type RaceTire struct{}
type GeneralCar struct{}
type GeneralTire struct{}

func (car RaceCar) GetTireType() Tire {
    return RaceTire{}
}

func (car GeneralCar) GetTireType() Tire {
    return GeneralTire{}
}

func findTireType(c Car) {
    tire := c.GetTireType()
    switch tire.(type) {
    case RaceTire:
        fmt.Printf("Type: RaceTire. Value %v", tire.(RaceTire))
    case GeneralTire:
        fmt.Printf("Type: GeneralTire. Value %v", tire.(GeneralTire))
    default:
        fmt.Printf("Unknown Tire\n")
    }
}

func main() {
    rc := RaceCar{}
    findTireType(rc)
}

  • Related