Generic way to test for initial in go

huangapple go评论150阅读模式
英文:

Generic way to test for initial in go

问题

A: 在Go语言中,测试BarStruct是否为初始值的正确方法是使用reflect.DeepEqual函数进行比较。首先,导入reflect包,然后使用reflect.DeepEqual(fc, BarStruct{})来比较fcBarStruct{}是否相等。这将递归地比较结构体的每个字段,包括map类型的字段。

B: 在Go语言中,没有一种通用的方法可以测试任何变量是否为初始值。不同类型的变量可能有不同的初始值,因此需要根据变量的类型和定义的初始值进行相应的测试。

英文:

Is there a generic way to test a variable for initial in Go?

Given these test:

  1. package main
  2. import "fmt"
  3. type FooStruct struct {
  4. A string
  5. B int
  6. }
  7. type BarStruct struct {
  8. A string
  9. B int
  10. C map[int]string
  11. }
  12. func main() {
  13. // string isinital test
  14. var s string
  15. fmt.Println(s == "")
  16. // int isinital test
  17. var i int
  18. fmt.Println(i == 0)
  19. // primitive struct isinital test
  20. var fp FooStruct
  21. fmt.Println(fp == FooStruct{})
  22. // complex struct isinital test
  23. // fail -> invalid operation: fc == BarStruct literal (struct containing map[int]string cannot be compared)
  24. var fc BarStruct
  25. fmt.Println(fc == BarStruct{})
  26. // map isinital test
  27. var m map[string]int
  28. fmt.Println(len(m) == 0)
  29. // map isinital test
  30. // fail -> invalid operation: m == map[string]int literal (map can only be compared to nil)
  31. fmt.Println(m == map[string]int{})
  32. }

A: What is the proper way to test BarStruct for initial?

B: Is there a generic way to test any var for is initial?

答案1

得分: 1

你可以使用reflect.DeepEqual

  1. bs := BarStruct{}
  2. fmt.Println(reflect.DeepEqual(bs, BarStruct{}))
  3. // 输出:
  4. // true

Playground: http://play.golang.org/p/v11bkKUhXQ.

编辑: 你还可以定义一个名为isZero的辅助函数,如下所示:

  1. func isZero(v interface{}) bool {
  2. zv := reflect.Zero(reflect.TypeOf(v)).Interface()
  3. return reflect.DeepEqual(v, zv)
  4. }

这个函数适用于任何类型:

  1. fmt.Println(isZero(0))
  2. fmt.Println(isZero(""))
  3. fmt.Println(isZero(bs))
  4. fmt.Println(isZero(map[int]int(nil)))
英文:

You can use reflect.DeepEqual:

  1. bs := BarStruct{}
  2. fmt.Println(reflect.DeepEqual(bs, BarStruct{}))
  3. // Output:
  4. // true

Playground: http://play.golang.org/p/v11bkKUhXQ.

EDIT: you can also define an isZero helper function like this:

  1. func isZero(v interface{}) bool {
  2. zv := reflect.Zero(reflect.TypeOf(v)).Interface()
  3. return reflect.DeepEqual(v, zv)
  4. }

This should work with any type:

  1. fmt.Println(isZero(0))
  2. fmt.Println(isZero(""))
  3. fmt.Println(isZero(bs))
  4. fmt.Println(isZero(map[int]int(nil)))

huangapple
  • 本文由 发表于 2015年11月3日 18:59:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/33497407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定