Constructors in Go

前端 未结 11 1534
挽巷
挽巷 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 05:42

    There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.

    package main
    
    import "fmt"
    
    type Thing struct {
        Name string
        Num int
    }
    
    func (t *Thing) Init(name string, num int) {
        t.Name = name
        t.Num = num
    }
    
    func main() {
        t := new(Thing)
        t.Init("Hello", 5)
        fmt.Printf("%s: %d\n", t.Name, t.Num)
    }
    

    The result is:

    Hello: 5
    

提交回复
热议问题