maps

Code

basic_map_example.odin ¶
76 linesSource

1#+feature dynamic-literals
2package maps
3
4import "core:fmt"
5
6/*
7	Maps in Odin maps keys to value, and have a zero value of nil
8	This data structure is called a hash map or dictionary in other languages
9*/
10main :: proc() {
11	m := make(map[string]int)
12	defer delete(m)
13
14	m["Alice"] = 1
15	m["Bob"] = 2
16
17	fmt.println(m["Alice"])
18	// 1
19	fmt.println(m["Bob"])
20	// 2
21
22	// Check if a key exists for a map
23	alice_exists := "Alice" in m
24
25	if alice_exists {
26		fmt.println("Hurray, Alice is included!")
27	} else {
28		fmt.println("Please be sure to include Alice to the party :(")
29	}
30
31	fmt.println("Length of map is", len(m))
32
33	// Remove a value associated with a key
34	deleted_key, deleted_value := delete_key(&m, "Alice")
35
36	fmt.println("We have now removed key", deleted_key, "with value", deleted_value)
37	// We have now removed key Alice with value 1
38
39	// Or we can empty the whole map using clear 
40	clear(&m)
41
42
43	// We will now store actors in a map 
44	Actor :: struct {
45		age:    int,
46		salary: int,
47	}
48
49	actors := make(map[string]Actor)
50	defer delete(actors)
51
52	// Insert actors into the map with their age and salary
53	actors["Alice"] = {45, 140_000}
54	actors["Bob"] = {36, 120_000}
55
56	// Change the value of one actor
57	value, ok := &actors["Alice"]
58	if ok {
59		// If the key exists, we can dereference the map to change the value for given key
60		value^ = {36, 200_000}
61	}
62
63	// Iterating over a map
64	for k, v in actors {
65		fmt.println("Name:", k, "Age:", v.age, "Salary:", v.salary)
66	}
67
68	// To enable compound literals, '#feature dynamic-literals' must be added at the top of the file.
69	m2 := map[string]int {
70		"Bob"   = 10,
71		"Chloe" = 20,
72	}
73
74	// Print a map for debugging purposes
75	fmt.println(m2)
76}

Declarations Used 1