Iota to define keys on a Go map? - go

Let's suppose we have a map[int]string and we want to define it like this:
var a map[int]string = {
1: "some"
3: "value"
4: "maintained"
7: "manually"
// more 100 entries...
}
I would like to maintain the values manually because they have no pattern, but the keys have. Is there a way to maintain the key list just like we do with enum values using 1 << 1 + iota?
I'm not asking if it's possible to use iota as a map key (unfortunately it's not AFAIK), just if there is an equally elegant way to create the keys on a defined sequence.

Your best bet is to store the ordered values as a slice, and then use an init function to generate the map like this:
var a map[int]string
var vals = []string{
"some",
"value",
"maintained",
"manually",
}
func init() {
a = make(map[int]string)
for idx, val := range vals {
a[idxToKey(idx)] = val
}
}
func idxToKey(i int) int {
return 1<<1 + i
}
Run it on the Go Playground.
You can change idxToKey to be whatever transformation you want. I've used the one you gave in this case, but it could be anything. The argument goes where you'd normally put the iota keyword.

One way would be have an array/slice of all the words and loop through similar to this;
var words []string
var a map[int]string
for i, v := range words {
a[1 << 1 + i] = v
}

Related

Remove all map key in Golang [duplicate]

I'm looking for something like the c++ function .clear() for the primitive type map.
Or should I just create a new map instead?
Update: Thank you for your answers. By looking at the answers I just realized that sometimes creating a new map may lead to some inconsistency that we don't want. Consider the following example:
var a map[string]string
var b map[string]string
func main() {
a = make(map[string]string)
b=a
a["hello"]="world"
a = nil
fmt.Println(b["hello"])
}
I mean, this is still different from the .clear() function in c++, which will clear the content in the object.
You should probably just create a new map. There's no real reason to bother trying to clear an existing one, unless the same map is being referred to by multiple pieces of code and one piece explicitly needs to clear out the values such that this change is visible to the other pieces of code.
So yeah, you should probably just say
mymap = make(map[keytype]valtype)
If you do really need to clear the existing map for whatever reason, this is simple enough:
for k := range m {
delete(m, k)
}
Unlike C++, Go is a garbage collected language. You need to think things a bit differently.
When you make a new map
a := map[string]string{"hello": "world"}
a = make(map[string]string)
the original map will be garbage-collected eventually; you don't need to clear it manually. But remember that maps (and slices) are reference types; you create them with make(). The underlying map will be garbage-collected only when there are no references to it.
Thus, when you do
a := map[string]string{"hello": "world"}
b := a
a = make(map[string]string)
the original array will not be garbage collected (until b is garbage-collected or b refers to something else).
// Method - I , say book is name of map
for k := range book {
delete(book, k)
}
// Method - II
book = make(map[string]int)
// Method - III
book = map[string]int{}
Go 1.18 and above
You can use maps.Clear. The function belongs to the package golang.org/x/exp/maps (experimental and not covered by the compatibility guarantee)
Clear removes all entries from m, leaving it empty.
Example usage:
func main() {
testMap := map[string]int{"gopher": 1, "badger": 2}
maps.Clear(testMap)
fmt.Println(testMap)
testMap["zebra"] = 2000
fmt.Println(testMap)
}
Playground: https://go.dev/play/p/qIdnGrd0CYs?v=gotip
If you don't want to depend on experimental packages, you can copy-paste the source, which is actually extremely simple:
func Clear[M ~map[K]V, K comparable, V any](m M) {
for k := range m {
delete(m, k)
}
}
IMPORTANT NOTE: just as with the builtin delete — which the implementation of maps.Clear uses —, this does not remove irreflexive keys from the map. The reason is that for irreflexive keys, by definition, x == x is false. Irreflexive keys are NaN floats and every other type that supports comparison operators but contains NaN floats somewhere.
See this code to understand what this entails:
func main() {
m := map[float64]string{}
m[1.0] = "foo"
k := math.NaN()
fmt.Println(k == k) // false
m[k] = "bar"
maps.Clear(m)
fmt.Printf("len: %d, content: %v\n", len(m), m)
// len: 1, content: map[NaN:bar]
a := map[[2]float64]string{}
a[[2]float64{1.0, 2.0}] = "foo"
h := [2]float64{1.0, math.NaN()}
fmt.Println(h == h) // false
a[h] = "bar"
maps.Clear(a)
fmt.Printf("len: %d, content: %v\n", len(a), a)
// len: 1, content: map[[1 NaN]:bar]
}
Playground: https://go.dev/play/p/LWfiD3iPA8Q
A clear builtin is being currently discussed (Autumn 2022) that, if added to next Go releases, will delete also irreflexive keys.
For the method of clearing a map in Go
for k := range m {
delete(m, k)
}
It only works if m contains no key values containing NaN.
delete(m, k) doesn't work for any irreflexive key (such as math.NaN()), but also structs or other comparable types with any NaN float in it. Given struct{ val float64 } with NaN val is also irreflexive (Quote by blackgreen comment)
To resolve this issue and support clearing a map in Go, one buildin clear(x) function could be available in the new release, for more details, please refer to add clear(x) builtin, to clear map, zero content of slice, ptr-to-array
If you are trying to do this in a loop, you can take advantage of the initialization to clear out the map for you. For example:
for i:=0; i<2; i++ {
animalNames := make(map[string]string)
switch i {
case 0:
animalNames["cat"] = "Patches"
case 1:
animalNames["dog"] = "Spot";
}
fmt.Println("For map instance", i)
for key, value := range animalNames {
fmt.Println(key, value)
}
fmt.Println("-----------\n")
}
When you execute this, it clears out the previous map and starts with an empty map. This is verified by the output:
$ go run maptests.go
For map instance 0
cat Patches
-----------
For map instance 1
dog Spot
-----------

How to write a bidirectional mapping in Go?

I am writing a simple console game and would like to map a player to a symbol. With two players my approach looks like this:
func playerToString(p player) string {
if p == 0 {
return "X"
}
return "O"
}
func stringToPlayer(s string) player {
if s == "X" {
return 0
}
return 1
}
Of cause you could also write this as two maps mapping int to string and string to int. Both the above approach and the map approach seem error-prone. Is there a more idiomatic way to write this in go? Maybe some non-iota enum way?
[I assume your example is just minimal and that your actual mapping has more than two options. I also assume you meant bi-directonal mapping]
I would write one map:
var player2string = map[int]string{
0: "0",
1: "X",
// etc...
}
And then would create a function to populate a different map string2player programmatically. Something like this:
var player2string = map[int]string{
0: "0",
1: "X",
// etc...
}
var string2player map[string]int = convertMap(player2string)
func convertMap(m map[int]string) map[string]int {
inv := make(map[string]int)
for k, v := range m {
inv[v] = k
}
return inv
}
func main() {
fmt.Println(player2string)
fmt.Println(string2player)
}
Try it on the Go playground
In addition to Eli's answer, two other changes you could make. You could make the to-symbol function a method of the player type. And because the player values are integers (sequential starting from zero), you can use a slice instead of a map to store the int-to-symbol mapping -- it's a bit more efficient to store and for lookup.
type player int
var playerSymbols = []string{"X", "O", "A", "B", "C", "D", "E", "F", "G", "H"}
func (p player) Symbol() string {
if int(p) < 0 || int(p) >= len(playerSymbols) {
return "?" // or panic?
}
return playerSymbols[p]
}
This method signature could even be String() string so it's a fmt.Stringer, which can be useful for printing stuff out and debugging.
Assuming you don't need any specific mapping and the player integer values have the sequence 0,1,2,3,...,25, you can generate the players symbols directly without using the maps as shown in following snippet :-
type player int
func ToSymbol(p player) string {
return fmt.Sprintf("%c", 'A' + p)
}
func ToPlayer(symbol string) player {
return player([]rune(symbol)[0] - 'A')
}

Is it possible to pass a field (not its value) as an argument in golang?

I have a program that is creating different leaderboards based on different fields in a slice of structs. This requires sorting the slice many times based on different fields where the only thing that is changing in the logic is the field being compared.
Is there a way to encapsulate this repeated logic by passing a field (not its value) as an argument to a function?
For clarification, here is rough approximation of the approach I am taking now:
type Person struct {
Name string
Stat1 int
Stat2 float64
}
person1 := Person{"Alice", 10, 2.0}
person2 := Person{"Bob", 12, 1.0}
person3 := Person{"Zach", 14, 0.1}
people := []Person{person1, person2, person3}
// Sorting based on one field
sort.Slice(people, func(i, j int) bool {
// Comparison logic that depends on comparing the Stat1 field
})
for i, p := range people {
fmt.Println(fmt.Sprint(i+1) + " - " + p.Name + " with " + fmt.Sprint(people[i].Stat1))
}
// Sorting based on another field
sort.Slice(people, func(i, j int) bool {
// Comparison logic that depends on comparing the Stat2 field
// but is otherwise identical to the comparison logic above
})
for i, p := range people {
fmt.Println(fmt.Sprint(i+1) + " - " + p.Name + " with " + fmt.Sprintf("%.1f", people[i].Stat2))
}
// Many, many more of these...
Ideally I'd be able to do something like this (but think this may be impossible without generics):
func sortSliceByField(people []Person, fieldToSortOn PersonField) []Person {
// Repeated sort logic on the field passed as an argument
}
The repetitiveness of the code you displayed would not benefit from the solution you propose. However, you can make it a bit more structured by using something like this:
var SortOptions = map[string]func([]Person) func(int,int)bool {
"stat1": func(people []Person) func(int,int) bool {
return func(i,j int) bool { return people[i].Stat1<people[j].Stat1 }
},
"stat2": func(people []Person) func(int,int) bool {
return func(i,j int) bool { return people[i].Stat2<people[j].Stat2 }
},
}
Then you can do:
sort.Slice(people,SortOptions["stat1"](people))

DeDuplicate Array of Structs

I have an array of struct and I want to remove all the duplicates element but keep the last element in the array. Something similar to hashmap where I can update the last struct matched every time to the new array
I have a struct something like this
type samplestruct struct {
value1 string
value2 string
value3 string
value4 string
value5 string
}
In my array of struct if value1, value2 and value3 of any struct is same , remove all the duplicates and keep the last struct.
func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
for _, v := range sample {
skip := false
for _, u := range unique {
if v.value1 == u.value1 && v.value2 == u.value2 && v.value3 == u.value3 {
skip = true
break
}
}
if !skip {
unique = append(unique, v)
}
}
return unique
}
This code return me the first struct that matched the condition provided but I want the last struct that matches the condition
Given Input -
[
samplestruct{"ram","rahim","india","34","india"},
samplestruct{"ram","rahim","india","38","America"},
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","35","hawai"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]
ExpectedOutput -
[
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]
The code in the question is almost there. When a matching element is found in unique, overwrite the element with the current value:
func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
sampleLoop:
for _, v := range sample {
for i, u := range unique {
if v.value1 == u.value1 && v.value2 == u.value2 && v.value3 == u.value3 {
unique[i] = v
continue sampleLoop
}
}
unique = append(unique, v)
}
return unique
}
The map-based approaches shown in other answers may be more appropriate depending on the size of the data set and number of surviving elements. Here's a correct implementation of the map approach:
func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
type key struct{ value1, value2, value3 string }
m := make(map[key]int)
for _, v := range sample {
k := key{v.value1, v.value2, v.value3}
if i, ok := m[k]; ok {
// Overwrite previous value per requirement in
// question to keep last matching value.
unique[i] = v
} else {
// Unique key found. Record position and collect
// in result.
m[k] = len(unique)
unique = append(unique, v)
}
}
return unique
}
Probably you should use a map here, use the important values as the key, when you encounter a duplicate and check for the key, you replace the value in the map.
Currently you are adding the values to the unique array if you haven't encountered them before, and then if you encounter one in the array after, you skip it. This is why you are only adding the first encounter of each struct which is the opposite of what you want.
You could either produce the key to the map as a concatenation of your important values (1 to 3), or use a struct of the three values as a key, and build the new key struct for each items and then search for it in the map.
Using a map will also be more performant than an array, as you can lookup much quicker in a map than iterating the unique array each time.
Nice little exercise, here is one solution which I will explain below:
package main
import "fmt"
func main() {
all := []person{
{"ram", "rahim", "india", "34", "india"},
{"ram", "rahim", "india", "38", "America"},
{"ram", "rahim", "india", "40", "Jamica"},
{"amit", "rawat", "bangladesh", "35", "hawai"},
{"amit", "rawat", "bangladesh", "36", "india"},
}
var deduped []person
// add the last occurrence always
for i := len(all) - 1; i >= 0; i-- {
if !contains(deduped, all[i]) {
// "append" to the front of the array
deduped = append([]person{all[i]}, deduped...)
}
}
for _, x := range deduped {
fmt.Println(x)
}
}
type person [5]string
func eq(a, b person) bool {
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]
}
func contains(list []person, x person) bool {
for i := range list {
if eq(x, list[i]) {
return true
}
}
return false
}
We step through the input array backwards in order to catch the last of multiple equal items. Then we want to append that item to the back of the deduped array. That is why we revert the append operation, creating a new temporary one-item person slice and append the previous to it.
Efficiency-wise, this solution has some drawbacks, appending to the one-item slice will use O(n²) space as it produces a new slice every time, pre-allocating an array of len(all), appending to it, and reversing it afterwards would solve that problem.
The second performance issue that might arise if you do this for a zillion persons is the contains function which is O(n²) lookups for the program. This could be solved with a map[person]bool.
Use a map. First scan the list and set up a map with the first 3 values as the key for the map. The map value for each key will be the last found
Then walk the map it will be set to the correct values
package main
import (
"fmt"
"strings"
)
type samplestruct struct {
value1 string
value2 string
value3 string
value4 string
value5 string
}
func mkey(x samplestruct) string {
return strings.Join([]string{x.value1, x.value2, x.value3}, "-")
}
func main() {
cm := make(map[string]samplestruct)
exampledata := []samplestruct{samplestruct{"ram", "rahim", "india", "34", "india"},
samplestruct{"ram", "rahim", "india", "38", "America"},
samplestruct{"ram", "rahim", "india", "40", "Jamica"},
samplestruct{"amit", "rawat", "bangladesh", "35", "hawai"},
samplestruct{"amit", "rawat", "bangladesh", "36", "india"}}
for _, x := range exampledata {
k := mkey(x)
cm[k] = x
}
for x := range cm {
fmt.Println(cm[x])
}
}
https://play.golang.org/p/ITD0VjhFQEk

Golang: declaring maps and slices with iota values

I have this Go code:
package main
import "fmt"
type baseGroup int
const (
fooGroup baseGroup = iota + 1
barGroup
)
var groups = [...]string{
fooGroup: "foo",
barGroup: "bar",
}
var xGroups = map[baseGroup]string{
fooGroup: "foo",
barGroup: "bar",
}
func main() {
fmt.Println("groups")
for k, v := range groups {
fmt.Println(k, v)
}
fmt.Println("xGroups")
for k, v := range xGroups {
fmt.Println(k, v)
}
}
If i run the code i get:
groups
0
1 foo
2 bar
xGroups
1 foo
2 bar
I'm wondering why the different outputs?
You're expecting range to behave the same on both types but in the first case it's ranging over an array and you just have an empty index 0. The value being stored in k is the current index; 0, 1, 2. In your second example you're ranging over the map and getting the key stored in k which only contains 1 and 2.
You might be wondering how is this happening? It's because this;
var groups = [...]string{
fooGroup: "foo",
barGroup: "bar",
}
Little confusing (imo very bad) code is giving you this;
var groups = [...]string{
1: "foo",
2: "bar",
}
Which is causing groups to be allocated/initialized with an empty string in index 0. Of course, the map doesn't need a key 0 to let you put something there in key 1 so it doesn't suffer from the same problems. If this is anything more than an exercise to demonstrate the features of the language I would highly recommend you get rid of the intentionally obfuscated code and use more clear constructs for constants, types and initialization.
If your skeptical about that mechanism add the following lines to your main and you can clearly see
fmt.Printf("Lenght of groups is %d and index 0 is %s\n", len(groups), groups[0])
fmt.Printf("Lenght of xGroups is %d\n", len(xGroups))

Resources