Home > Backend Development > Golang > How to restrict interface{} to a specific type

How to restrict interface{} to a specific type

WBOY
Release: 2024-02-05 22:57:04
forward
607 people have browsed it

How to restrict interface{} to a specific type

Question content

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{}
    ....
    }
}
Copy after login

The following are the respective structure types:

type Truck struct {
    Foo string
}

type Car struct {
    Bar string
}
Copy after login

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?


Correct answer


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
}

Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template