简体   繁体   中英

Static member of a struct in Golang

Say I have a struct:

type DriverData struct {
    TypePath string = "Foo.Bar.DriverData"
}

I want to be able to reference TypePath without having to create an instance of the struct, something like:

typePath := DriverData.TypePath

but that's not possible in Golang.

So I was wondering - maybe there is a way to create a map, and associate the type with a string, something like:

type DriverData struct {

}

type PilotData struct {

}

type BoatmasterData struct {

}

typeMap := map[struct]string{
   DriverData: "Foo.Bar.DriverData",
   PilotData:   "Foo.Bar.PilotData",
   BoatmasterData: "Foo.Bar.BoatmasterData",
}

Question:

Is this the best approach to create static properties on a struct? Storing the static properties in a map like this?

You can define methods to give you those values:

type DriverData struct {
}

func (DriverData) Path() string {
    return "Foo.Bar.DriverData"
}

type PilotData struct {
}

func (PilotData) Path() string {
    return "Foo.Bar.PilotData"
}

type BoatmasterData struct {
}

func (BoatmasterData) Path() string {
    return "Foo.Bar.BoatmasterData"
}

Does that do what you want?

See https://play.golang.org/p/zR7RZwMVEdf .

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