Last active
August 29, 2015 13:56
-
-
Save allanruin/8877748 to your computer and use it in GitHub Desktop.
测试IsValid函数对于未初始化的结构体域是否返回false
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Person struct { | |
Name string | |
Age int | |
Weight float64 | |
} | |
func main() { | |
p := new(Person) | |
p2 := &Person{"allan", 18, 62.3} | |
TryIsValid(p) | |
TryIsValid(p2) | |
TryIsZero(p) | |
TryIsZero(p2) | |
} | |
// 看到文档说“IsValid returns true if v represents a value. It returns false | |
// if v is the zero Value.” | |
// 同时可以看到函数reflect.Zero(typ Type)返回的是是Type类型的零值。按我的理解 | |
// 这种为(广义)“零值”的应该就是属于Zero了,所以IsValid应该返回 false才对。 | |
// 实际上,及时对于一个未曾初始化的结构体里的field, IsValid返回的还是true | |
// SO上的这个问题问到了相似的情形: | |
// http://stackoverflow.com/questions/13901819/quick-way-to-detect-empty-values-via-reflection-in-go | |
func TryIsValid(p *Person) { | |
v := reflect.ValueOf(p) | |
ind := reflect.Indirect(v) | |
num := ind.NumField() | |
fmt.Println("****************************") | |
for i := 0; i < num; i++ { | |
fv := ind.Field(i) | |
if fv.IsValid() { | |
fmt.Println("Valid:", fv) | |
} else { | |
fmt.Println("Not a valid field value: ", fv) | |
} | |
} | |
fmt.Println("****************************\n") | |
} | |
func TryIsZero(p *Person) { | |
v := reflect.ValueOf(p) | |
ind := reflect.Indirect(v) | |
num := ind.NumField() | |
fmt.Println("****************************") | |
for i := 0; i < num; i++ { | |
fv := ind.Field(i) | |
if IsZero(fv) { | |
fmt.Println("Zero:", fv) | |
} else { | |
fmt.Println("Not Zero: ", fv) | |
} | |
} | |
fmt.Println("****************************\n") | |
} | |
func IsZero(v interface{}) bool { | |
return v == reflect.Zero(reflect.TypeOf(v)).Interface() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
out puts as:
Valid:
Valid:
Valid:
Valid: allan
Valid:
Valid:
Not Zero:
Not Zero:
Not Zero:
Not Zero: allan
Not Zero:
Not Zero: