英文:
It is an empty value struct nil
问题
看一下下面的代码片段。
package main
import "fmt"
type Empty struct {
Field1, Field2 string
}
func main() {
value := Empty{}
fmt.Println(value == nil)
fmt.Printf("%p", &value)
}
我遇到了编译错误
./empty_struct.go:19: 无法将nil转换为Empty类型
我该如何检查一个值结构体的类型,以确定它是否为空?
英文:
Look at the following code snippet.
package main
import "fmt"
type Empty struct {
Field1, Field2 string
}
func main() {
value := Empty{}
fmt.Println(value == nil)
fmt.Printf("%p", &value)
}
I've got compiler error
./empty_struct.go:19: cannot convert nil to type Empty
How can I check a value struct type, if it is empty or not?
答案1
得分: 13
指针、切片、通道、接口和映射是唯一可以与nil进行比较的类型。结构体值不能与nil进行比较。
如果结构体的所有字段都是可比较的(就像你的示例中一样),那么你可以与结构体的已知零值进行比较:
fmt.Println(value == Empty{})
如果结构体包含不可比较的字段(切片、映射、通道),那么你需要编写代码来检查每个字段:
func IsAllZero(v someStructType) bool {
return v.intField == 0 && v.stringField == "" && v.sliceField == nil
}
...
fmt.Println(isAllZero(value))
英文:
Pointers, slices, channels, interfaces and maps are the only types that can be compared to nil. A struct value cannot be compared to nil.
If all fields in the struct are comparable (as they are in your example), then you can compare with a known zero value of the struct:
fmt.Println(value == Empty{})
If the struct contains fields that are not comparable (slices, maps, channels), then you need to write code to check each field:
func IsAllZero(v someStructType) bool {
return v.intField == 0 && v.stringField == "" && v.sliceField == nil
}
...
fmt.Println(isAllZero(value))
答案2
得分: 4
你可以定义一个结构体的“nil”值,例如:
var nilEmpty = Empty{}
fmt.Println(value == nilEmpty)
nil
只能用于指针类型(切片、通道、接口和映射)。
请记住,如果结构体中有切片或任何不可比较的值,结构体的相等性并不总是有效,你需要使用reflect.DeepEqual
。
来自http://golang.org/ref/spec#Comparison_operators:
如果结构体的所有字段都是可比较的,那么结构体值是可比较的。如果两个结构体值的对应非空字段相等,则它们是相等的。
英文:
You can define a "nil" value of a struct, for example:
var nilEmpty = Empty{}
fmt.Println(value == nilEmpty)
nil
can only be used for pointer-types (slices, channels, interfaces and maps).
Keep in mind that struct equality doesn't always work if you have slices or any incomparable value in the struct, you would have to use reflect.DeepEqual
then.
From http://golang.org/ref/spec#Comparison_operators:
>> Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
答案3
得分: 2
这是一个值类型,类似于int
,因此它不能为nil。只有指针类型和接口类型可以为nil。如果你想允许一个nil值,可以将其定义为指针类型:
value := &Empty{}
英文:
It is a value type, like int
, therefore it cannot be nil. Only pointer and interface types can be nil. If you want to allow a nil value, make it a pointer:
value := &Empty{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论