Constructors in Go

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

    There are actually two accepted best practices:

    1. Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
    2. Provide a function func New() YourTyp or if you have several such types in your package functions func NewYourType1() YourType1 and so on.

    Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New... functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)

提交回复
热议问题