Go語言如何判斷是否是零值


通過封裝IsZeroOfUnderlyingType方法判斷,代碼如下

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name string
	Age  int
}

func IsZeroOfUnderlyingType(x interface{}) bool {
	return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}

func main() {
	var person Person //定義一個零值

	fmt.Println(IsZeroOfUnderlyingType(person)) //零值結構體,輸出true

	person.Name = "chenqiognhe"                 //結構體屬性Name賦值
	fmt.Println(IsZeroOfUnderlyingType(person)) //輸出false

	fmt.Println(IsZeroOfUnderlyingType(person.Age)) //Age仍是零值,輸出true

	person.Age = 18                                 //Age賦值
	fmt.Println(IsZeroOfUnderlyingType(person.Age)) //輸出false
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM