Home >Backend Development >Golang >How to restrict interface{} to a specific type
I am using go and have a factory function that returns different types of objects based on the requested identifier:
func newobject(id string) interface{} { switch id { case "truck": return truck{} case "car": return car{} .... } }
The following are the respective structure types:
type Truck struct { Foo string } type Car struct { Bar string }
As you can see, trucks and cars have nothing in common. The problem arises because I now have to deal with the overly broad type interface{}
when calling newobject(..)
. I know there are generics, but this requires keeping a list of all supported types in a type constraint, which complicates things in my code base.
Basically I'm looking for a way how to use inheritance here, which of course go doesn't support. What's the alternative?
newobject(..)
Function can be implemented with the support of generics. You don't need to keep a list of all supported types in a type constraint.
func NewObject[T any](id string) T { var vehicle any switch id { case "truck": vehicle = Truck{ Foo: "foo", } case "car": vehicle = Car{ Bar: "bar", } } if val, ok := vehicle.(T); ok { return val } var otherVehicle T fmt.Printf("Not implemented. Returning with default values for \"%v\"\n", id) return otherVehicle }
You can see the full example here.
The above is the detailed content of How to restrict interface{} to a specific type. For more information, please follow other related articles on the PHP Chinese website!