Constructors in Go

前端 未结 11 1533
挽巷
挽巷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 06:00

    I am new to go. I have another pattern taken from other languages, that have constructors. And will work in go.

    1. Create an init method.
    2. Make the init method an (object) once routine. It only runs the first time it is called (per object).
    func (d *my_struct) Init (){
        //once
        if !d.is_inited {
            d.is_inited = true
            d.value1 = 7
            d.value2 = 6
        }
    }
    
    1. Call init at the top of every method of this class.

    This pattern is also useful, when you need late initialisation (constructor is too early).

    Advantages: it hides all the complexity in the class, clients don't need to do anything.

    Disadvantages: you must remember to call Init at the top of every method of the class.

提交回复
热议问题