Constructors in Go

前端 未结 11 1532
挽巷
挽巷 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:01

    another way is;

    package person
    
    type Person struct {
        Name string
        Old  int
    }
    
    func New(name string, old int) *Person {
        // set only specific field value with field key
        return &Person{
            Name: name,
        }
    }
    

提交回复
热议问题