go struct 设置默认值

定义一个struct ,想设定默认值,如下面的形式:

type Person struct {
    Name string
    Age int
    Weight int
    Foo string = "Person"
}

go 没有这样的使用方式,只能通过下面的方式实现:

func NewPerson() *Person {
    return &Person{Foo:"Person"}
}

//or

func NewPerson() Person {
    return Person{Foo:"Person"}
}

一个完整的例子

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)
}

下面是更复杂的例子:

package main

import (
    "fmt"
)

type Object struct {
    Type int
    Name string
}

func NewObject(obj *Object) *Object {
    if obj == nil {
        obj = &Object{}
    }
    // Type has a default of 1
    if obj.Type == 0 {
        obj.Type = 1
    }
    return obj
}

func main() {
    // create object with Name="foo" and Type=1
    obj1 := NewObject(&Object{Name: "foo"})
    fmt.Println(obj1)

    // create object with Name="" and Type=1
    obj2 := NewObject(nil)
    fmt.Println(obj2)

    // create object with Name="bar" and Type=2
    obj3 := NewObject(&Object{Type: 2, Name: "foo"})
    fmt.Println(obj3)
}
Relative Articles