Go struct tag能否设置默认值?

简介: Go struct tag能否设置默认值?

struct tag默认值



1. 需求背景


有时候gopher在marshal一个struct到json的时候,想要struct某些属性在没有值的情况下有默认值,但是按照现在marshar的作用下不会给struct的属性赋默认值,所以为了解决这个特殊需求,我们应该按照以下方案来解决。


2. 解决方案


利用反射,因为通过反射,我们可以拿到tag属性,进而对默认字段做赋值操作


先看一段代码:


type test struct {
    Name     string `json:"name"`
    Addr     string `json:"addr" default:"localhost"`
    Port     uint   `json:"port" default:"8080"`
}
func MarshalJson(i interface{}) ([]byte, error) {
    typeof := reflect.TypeOf(i)
    valueof := reflect.ValueOf(i)
    for i := 0; i < typeof.Elem().NumField(); i++ {
        if valueof.Elem().Field(i).IsZero() {
            def := typeof.Elem().Field(i).Tag.Get("default")
            if def != "" {
                switch typeof.Elem().Field(i).Type.String() {
                case "int":
                    result, _ := strconv.Atoi(def)
                    valueof.Elem().Field(i).SetInt(int64(result))
                case "uint":
                    result, _ := strconv.ParseUint(def, 10, 64)
                    valueof.Elem().Field(i).SetUint(result)
                case "string":
                    valueof.Elem().Field(i).SetString(def)
                }
            }
        }
    }
    return json.Marshal(i)
}
func main() {
    t := &test{
        Name:     "test server",
    }
    data, err := MarshalJon(t)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(data))
}
结果:
{"name":"test server","addr":"localhost","port":8080}


3. 小结


其实在解析struct的时候golang本身已经为struct的属性按照类型赋默认值了,但是这个默认值在没有办法满足我们的需求的时候,这个时候就需要造轮子,别怕麻烦,解决问题才是王道。大家想想unmarshal的时候如何赋默认值呢?

相关文章
|
18天前
|
Go
Go - struct{} 实现 interface{}
Go - struct{} 实现 interface{}
30 9
|
2月前
|
JSON Go 数据格式
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(4)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
2月前
|
Java 编译器 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(3)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
2月前
|
存储 安全 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(2)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
2月前
|
Java Go 索引
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(1)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
3月前
|
Go 开发者
Golang深入浅出之-Go语言结构体(struct)入门:定义与使用
【4月更文挑战第22天】Go语言中的结构体是构建复杂数据类型的关键,允许组合多种字段。本文探讨了结构体定义、使用及常见问题。结构体定义如`type Person struct { Name string; Age int; Address Address }`。问题包括未初始化字段的默认值、比较含不可比较字段的结构体以及嵌入结构体字段重名。避免方法包括初始化结构体、自定义比较逻辑和使用明确字段选择器。结构体方法、指针接收者和匿名字段嵌入提供了灵活性。理解这些问题和解决策略能提升Go语言编程的效率和代码质量。
57 1
|
3月前
|
JSON Go 数据库
Go语言中tag的用处及详细介绍
【2月更文挑战第24天】
125 2
|
3月前
|
存储 缓存 编译器
Go语言解析Tag:深入探究实现原理
【2月更文挑战第20天】
175 2
|
存储 Go
Go空结构体struct {}
struct {}介绍、使用场景、和struct {}{}比较
84 0
|
8月前
|
编译器 Go
go struct 使用
go struct 使用
34 0