gpt4 book ai didi

go - 如何检查只包含一个 bool 字段的空结构

转载 作者:IT王子 更新时间:2023-10-29 02:30:54 24 4
gpt4 key购买 nike

type Test struct { }

我知道这可能是通过 (Test{}) == test 检查空结构的方法。但是,它似乎不适用于仅包含一个 bool 字段的结构。考虑这个例子:

package main

import "fmt"

type Test struct {
Foo bool
}

func main() {
empty := Test{}
test1 := Test{Foo: true}
test2 := Test{Foo: false}
fmt.Println(Test{} == test1) //False yay
fmt.Println(Test{} == test2) //True oh no ...
fmt.Println(Test{} == empty) //True yay
}

基本上,== 认为包含 false 字段的结构与空结构相同。

是否有更好的方法来检查空结构,或者我是否遗漏了什么?

另外,你可能想知道为什么结构中只有一个字段,嗯,因为结构处于开发阶段,以后可能会有更多字段。

最佳答案

The Go Programming Language Specification

Struct types

A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly

// An empty struct.
struct {}

Composite literals

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

A literal may omit the element list; such a literal evaluates to the zero value for its type.

The zero value

When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.


type Test struct {
Foo bool
}

empty := Test{}

empty 不是空的。它是零值。

zeroValue := Test{}

或者,明确地,

zeroValue := Test{Foo: false}

关于go - 如何检查只包含一个 bool 字段的空结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55193850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com