可以使用struct tag来为struct字段分配默认值:


type Person struct {
    Name string `default:"John Doe"`
    Age  int    `default:"18"`
}

可以使用反射来设置默认值:


func setDefaultValues(s interface{}) {
    v := reflect.ValueOf(s)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
        return
    }
    t := v.Type()
    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        tag := t.Field(i).Tag.Get("default")
        if tag == "" {
            continue
        }
        switch f.Kind() {
        case reflect.String:
            f.SetString(tag)
        case reflect.Int:
            i, _ := strconv.Atoi(tag)
            f.SetInt(int64(i))
        }
    }
}

使用:


p := Person{}
setDefaultValues(&p)
fmt.Println(p)
// Output: {John Doe 18}