Constructors in Go

前端 未结 11 1523
挽巷
挽巷 2020-12-04 05:24

I have a struct and I would like it to be initialised with some sensible default values.

Typically, the thing to do here is to use a constructor but since go isn\'t

11条回答
  •  不思量自难忘°
    2020-12-04 06:08

    There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

    Supposing you have a struct like this :

    type Thing struct {
        Name  string
        Num   int
    }
    

    then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

    func NewThing(someParameter string) *Thing {
        p := new(Thing)
        p.Name = someParameter
        p.Num = 33 // <- a very sensible default value
        return p
    }
    

    When your struct is simple enough, you can use this condensed construct :

    func NewThing(someParameter string) *Thing {
        return &Thing{someParameter, 33}
    }
    

    If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

    func makeThing(name string) Thing {
        return Thing{name, 33}
    }
    

    Reference : Allocation with new in Effective Go.

提交回复
热议问题