Thursday, March 23, 2023
HomePythonGolang: Examine if a key exists in map

Golang: Examine if a key exists in map


Hello individuals! I’m working at ASAPP and loads of my work includes writing Golang code. That is the primary time I’m working with Golang full-time. I picked up a few methods from my colleagues and mentors right here and want to share them with you.

On this specific put up, I’ll speak in regards to the empty struct. There was a situation the place I wished to verify if two slices contained the identical parts or not. Go doesn’t present a straightforward manner to do that. So far as I do know, there isn’t a API for slices which offer us a approach to do one thing like this:

mySlice := []string{"Yasoob", "Ali", "Ahmed"}
mySlice.incorporates("Yasoob")

This can be a gross simplification of the particular downside I needed to tackle however the primary concept is identical. Now we will loop over the entire slice and verify if a worth exists by doing one thing like this:

var flag bool
for _, val := vary mySlice{
    if val == "Yasoob"{
        flag = true
    }
}

However this doesn’t scale very well. What if now we have hundreds of entries within the slice and now we have to verify for existence each second? Within the worst case situation, we must loop over the entire slice every time.

In such a situation we will use a map as a substitute of a slice. The only real motive for utilizing them is that the lookup is quite a bit sooner. Now you is perhaps asking that what ought to we map these strings to? And the reply is an empty struct! The reason is that an empty struct doesn’t take up any house! This fashion we is not going to get loads of additional house consumption overhead.

So now we will rewrite the code like this:

myMap := map[string]struct{}{
    "Yasoob": struct{}{},
    "Ali":    struct{}{},
}
_, okay := myMap["Yasoob"]
if okay{
    fmt.Println("exists!")
}

The best way it really works is {that a} map gives an excellent API for checking if a key exists or not. It offers two return values. The primary is the worth mapped to the important thing and the second is a boolean which tells us whether or not the important thing exists within the map or not.

The _ within the code above will get assigned the worth mapped with the important thing “Yasoob”. We don’t care in regards to the worth as it’s simply an empty struct so we simply discard it by assigning it to _. We do, nonetheless, care about whether or not the important thing was discovered or not. That’s the reason now we have a variable referred to as “okay”. If the important thing was discovered then okay will get a bool worth of true and if the important thing wasn’t discovered then it’ll get a worth of false. Easy eh?

Now you will have a pleasant approach to verify if one thing exists or not in quite a bit much less time!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments