gpt4 book ai didi

go - 如果某物不在 map 中,返回值取什么值?

转载 作者:数据小太阳 更新时间:2023-10-29 03:21:30 26 4
gpt4 key购买 nike

好的,按照这个:

How to check if a map contains a key in go?

if val, ok := m["foo"]; ok {
//do something here
}

很好,但我们为什么不能这样做:

val, ok := m["foo"]

if val == nil { // cannot compare val to nil

}

我收到一个编译错误,提示我无法将 val 与 nil 进行比较,但是 val 有什么值呢?我可以将它与什么进行比较,以确定它是否存在?

m的类型是这样的:

type m map[string]struct{}

最佳答案

The Go Programming Language Specification

Index expressions

For a of map type M: if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M.

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.


The Go Programming Language Specification

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. For struct literals the following rules apply:

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

对于您的示例,键入 struct{},从复合文字 struct{}{} 中省略元素列表作为零值。

例如,

package main

import "fmt"

func main() {
m := map[string]struct{}{}
val, ok := m["foo"]
fmt.Printf("%T %v\n", val, val)
if val == struct{}{} {
fmt.Println("==", val, ok)
}
}

Playground :https://play.golang.org/p/44D_ZfFDA77

输出:

struct {} {}
== {} false

The Go Programming Language Specification

Variable declarations

A variable declaration creates one or more variables, binds corresponding identifiers to them, and gives each a type and an initial value.

If a list of expressions is given, the variables are initialized with the expressions following the rules for assignments. Otherwise, each variable is initialized to its zero value.

If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment.

在您的示例中,您可以声明一个没有初始值的 struct{} 类型的变量,该变量将被初始化为 struct{} 类型的零值.

例如,

package main

import "fmt"

func main() {
m := map[string]struct{}{}
val, ok := m["foo"]
fmt.Printf("%T %v\n", val, val)
var zeroValue struct{}
if val == zeroValue {
fmt.Println("==", val, ok)
}
}

Playground :https://play.golang.org/p/_XcSCEeEKJV

输出:

struct {} {}
== {} false

关于go - 如果某物不在 map 中,返回值取什么值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025544/

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