Generic way to test for initial in go

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

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:

package main

import "fmt"

type FooStruct struct {
	A string
	B int
}

type BarStruct struct {
	A string
	B int
	C map[int]string
}

func main() {
	// string isinital test
	var s string
	fmt.Println(s == "")
	
	// int isinital test
	var i int
	fmt.Println(i == 0)
	
	// primitive struct isinital test
	var fp FooStruct
	fmt.Println(fp == FooStruct{})

	// complex struct isinital test
	// fail -> invalid operation: fc == BarStruct literal (struct containing map[int]string cannot be compared)
	var fc BarStruct
	fmt.Println(fc == BarStruct{})
	
	// map isinital test
	var m map[string]int
	fmt.Println(len(m) == 0)
	
	// map isinital test 
	// fail -> invalid operation: m == map[string]int literal (map can only be compared to nil)
	fmt.Println(m == map[string]int{})
}

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

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

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

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

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

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

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

You can use reflect.DeepEqual:

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

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

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

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

This should work with any type:

fmt.Println(isZero(0))
fmt.Println(isZero(""))
fmt.Println(isZero(bs))
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:

确定