Friday, April 22, 2022

Go vs Rust - HashMap

 HashMap

The concept of HashMap is present in almost all programming languages like Java, C++, Python, it has key-value pairs and through key, we can get values of the map. Keys are unique no duplicates allowed in the key but the value can be duplicated.

Go

Maps are Go’s built-in associative data type (sometimes called hashes or dicts in other languages).

package main
import "fmt"
func main() {
    m := make(map[string]int)
    m["k1"] = 7
    m["k2"] = 13
    fmt.Println("map:", m)
    v1 := m["k1"]
    fmt.Println("v1: ", v1)
    fmt.Println("len:", len(m))
    delete(m, "k2")
    fmt.Println("map:", m)
    _, prs := m["k2"]
    fmt.Println("prs:", prs)
    n := map[string]int{"foo": 1, "bar": 2}
    fmt.Println("map:", n)
}

To initialize a map with some data, use a map literal:

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}

Concurrency

Maps are not safe for concurrent use. One common way to protect maps is with sync.RWMutex.

var counter = struct{
    sync.RWMutex
    m map[string]int
}{m: make(map[string]int)}

To read from the counter, take the read lock:

counter.RLock()
n := counter.m["some_key"]
counter.RUnlock()
fmt.Println("some_key:", n)

To write to the counter, take the write lock:

counter.Lock()
counter.m["some_key"]++
counter.Unlock()

Rust

let mut gfg=HashMap::new();
// inserting records 
gfg.insert("Data Structures","90");
gfg.insert("Algorithms","99");
gfg.entry(String::from("Blue")).or_insert("50");

for (key, val) in gfg.iter() {
    println!("{} {}", key, val);
}

if gfg.contains_key( & "FAANG") {
   println!("yes it contains the given key well done gfg");
}

println!("len of gfg HashMap={}",gfg.len());

gfg.remove(& "key");
let value= gfg.get(&"Algorithms");

// Update after check
for word in text.split_whitespace() {
    let count = map.entry(word).or_insert(0);
    *count += 1;
}


No comments:

Post a Comment