使用空值创建地图

问题描述 投票:3回答:2

我只需要使用map作为键,我不需要存储值。所以我宣布了这样的地图:

modified_accounts:=make(map[int]struct{})

我们的想法是使用空结构,因为它不消耗存储空间。

但是,当我尝试向地图添加条目时,

modified_accounts[2332]=struct{}

我收到了一个编译错误:

./blockchain.go:291:28: type struct {} is not an expression

如何向地图添加空键而没有值?

go
2个回答
7
投票

你可以声明一个空变量

var Empty struct{}

func foo() {
    modified_accounts := make(map[int]struct{})
    modified_accounts[2332] = Empty
    fmt.Println(modified_accounts)
}

或者每次都创建一个新结构

func bar() {
    modified_accounts := make(map[int]struct{})
    modified_accounts[2332] = struct{}{}
    fmt.Println(modified_accounts)
}

要创建一个空的struct,你应该使用struct{}{}


2
投票

错误正是您在下面的行中看到的:

./blockchain.go:291:28:type struct {}不是表达式

表达式是evaluates to something(具有值的东西),struct{}是一种类型,并且您的语句试图将类型(右)分配给地图的键值,变量(左)

您需要的是创建此类型的变量,并将该变量作为值分配给地图的键。

通过使用:

var x struct{}
modified_accounts[2332] = x

要么

modified_accounts[2332] = struct{}{}

在上述任一方法中,您将创建struct{}类型的值,并将该值分配给地图的键。

© www.soinside.com 2019 - 2024. All rights reserved.