Creating map with empty values

Creating map with empty values



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


map


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 ?






To get to the heart of the issue: struct is a type. struct is an instance of that type.

– Adam Smith
Sep 8 '18 at 1:40


struct


struct






Why do you even use a map, then, and not a slice?

– Michael Hampton
Sep 8 '18 at 13:08






@MichaelHampton, maps guarantee duplicated entries are removed, slice will not do this.

– Nulik
Sep 8 '18 at 15:20




2 Answers
2



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


struct


struct



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)


evaluates to something


struct



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.


struct



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)