-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
88 lines (70 loc) · 2.43 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package immutable_test
import (
"encoding/json"
"fmt"
"github.com/reactivego/immutable"
)
func Example_map() {
var m immutable.Map[string, string]
m = m.Set("Hello", "World!")
fmt.Println(m)
// Output:
// {Hello:World!}
}
func ExampleMap() {
var m immutable.Map[string, int]
m = m.Set("first", 123).Set("second", 456).Set("first", 789)
m.Range(func(key string, value int) bool {
fmt.Println(key, value)
return true
})
// Unordered Output:
// first 789
// second 456
}
func ExampleMapX() {
// Key is comparable (i.e. == and !=) but not hashable.
// Notice that the key is a struct with unexported fields that are not
// marshalled by the default json.Marshal function.
type key struct{ A, B, c int }
// Map with a marshal function to convert the key to []byte for hashing.
m := immutable.MapWith[key, string](json.Marshal)
m = m.Set(key{1, 2, 3}, "Mammalia is the class of mammals.")
m = m.Set(key{1, 2, 4}, "Aves is the class of birds.")
b, e := json.Marshal(key{1, 2, 3})
fmt.Println(string(b), e)
fmt.Println(m.Get(key{1, 2, 3}))
fmt.Println(m.Get(key{1, 2, 4})) // same hash as key{1, 2, 3} because 'c' is not exported.
fmt.Println(m.Get(key{7, 8, 9}))
// Output:
// {"A":1,"B":2} <nil>
// Mammalia is the class of mammals.
// Aves is the class of birds.
}
func ExampleMapX_Set() {
// Key is comparable (i.e. == and !=) but not hashable.
type Key struct{ K1, K2 int64 }
type Topic struct{ Name, Description string }
// Map with a marshal function to convert the key to []byte for hashing.
m := immutable.MapWith[Key, Topic](json.Marshal)
m = m.Set(Key{1, 2}, Topic{"Theme", "This is a topic about theme"})
fmt.Println(m)
fmt.Println(m.Get(Key{1, 2}))
// Output:
// {{K1:1 K2:2}:{Name:Theme Description:This is a topic about theme}}
// {Theme This is a topic about theme}
}
func ExampleStore_Put() {
// Topic is an example of data where the key (i.e. Name) is part of the data.
type Topic struct{ Name, Description string }
store := immutable.StoreWith(func(t Topic) (string, Topic) {
return t.Name, t
})
store = store.Put(Topic{Name: "Aves", Description: "This topic is about birds."})
store = store.Put(Topic{Name: "Mammalia", Description: "This topic is about mammals"})
fmt.Printf("%+v\n", store.Get(Topic{Name: "Mammalia"}))
fmt.Printf("%+v\n", store.Get(Topic{Name: "Aves"}))
// Output:
// {Name:Mammalia Description:This topic is about mammals}
// {Name:Aves Description:This topic is about birds.}
}