Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating map with empty values

Tags:

go

I need to use a map for keys only, I don't need to store values. So I declared a map like this:

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

The idea is to use empty struct because it doesn't consume storage.

However, when I tried to add an entry to the map,

modified_accounts[2332]=struct{}

I got a compile error:

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

How do I add an empty key and no value to the map ?

like image 462
Nulik Avatar asked Sep 08 '18 00:09

Nulik


People also ask

How do you make an empty map?

We can create an empty Map using the emptyMap() method provided by the Java Collections module. This will form an empty Map that is serializable in nature. The method was introduced in Java 1.5 under the Collections Library.

How do you create an empty map in Golang?

To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.

Is map empty C++?

C++ map empty() function is used to check whether the map container is empty or not. It returns true, if the map container is empty (size is 0) otherwise false.

How do you initialize a map in go?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.


2 Answers

You can do it declaring a empty variable

var Empty struct{}

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

Or creating a new struct every time

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

To create a empty struct you should use struct{}{}

like image 86
Motakjuq Avatar answered Oct 04 '22 08:10

Motakjuq


The error is exactly what you see in the below line :

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

An expression is something that evaluates to something (something that has a value), struct{} is a type, and your statement is trying to assign a type(right) to a map's key's value, a variable(left)

What you need is to create a variable of this type, and assign that variable to the map's key as a value.

Either by using :

var x struct{}
modified_accounts[2332] = x

or

modified_accounts[2332] = struct{}{}

In either of the above way, you are creating a value of type struct{}, and assigning that value to the map's key.

like image 44
Tushar Avatar answered Oct 04 '22 06:10

Tushar