-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
112 lines (81 loc) · 2.28 KB
/
Copy pathexample_test.go
File metadata and controls
112 lines (81 loc) · 2.28 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package simplecache_test
import (
"fmt"
"time"
simplecache "github.com/MsN-12/simplecache"
)
type exampleNotifier interface {
Notify(string)
}
type exampleEmailNotifier struct {
Sent []string
}
func (n *exampleEmailNotifier) Notify(message string) {
n.Sent = append(n.Sent, message)
}
type exampleProfile struct {
Bio string
Tags []string
}
type exampleUser struct {
Name string
Profile exampleProfile
Notifier exampleNotifier
}
func Example() {
cache := simplecache.MustNew[string, int](time.Minute, simplecache.Identity[int])
cache.Set("answer", 42)
value, ok := cache.Get("answer")
fmt.Println(value, ok)
// Output: 42 true
}
func ExampleCloneSlice() {
cache := simplecache.MustNew[string, []string](time.Minute, simplecache.CloneSlice[string])
tags := []string{"go", "cache"}
cache.Set("tags", tags)
tags[0] = "changed"
cached, _ := cache.Get("tags")
fmt.Println(cached)
// Output: [go cache]
}
func ExampleCache_GetOrSet() {
cache := simplecache.MustNew[string, string](time.Minute, simplecache.Identity[string])
value, cached, err := cache.GetOrSet("name", func() (string, error) {
return "mohsen", nil
})
if err != nil {
return
}
fmt.Println(value, cached)
// Output: mohsen false
}
func ExampleCache_SetWithTTL() {
cache := simplecache.MustNew[string, string](time.Minute, simplecache.Identity[string])
_ = cache.SetWithTTL("session", "abc", 5*time.Minute)
fmt.Println(cache.Has("session"))
// Output: true
}
func ExampleMustNewAuto() {
cache := simplecache.MustNewAuto[string, exampleUser](time.Minute)
user := exampleUser{
Name: "Alice",
Profile: exampleProfile{Bio: "Software Engineer", Tags: []string{"go", "cache"}},
Notifier: &exampleEmailNotifier{Sent: []string{"created"}},
}
cache.Set("user", user)
user.Profile.Tags[0] = "changed"
user.Notifier.(*exampleEmailNotifier).Sent[0] = "changed"
cached, _ := cache.Get("user")
fmt.Println(cached.Name, cached.Profile.Tags, cached.Notifier.(*exampleEmailNotifier).Sent)
// Output: Alice [go cache] [created]
}
func ExampleCache_StartCleanup() {
cache := simplecache.MustNewAuto[string, string](time.Minute)
if err := cache.StartCleanup(time.Minute); err != nil {
return
}
defer cache.StopCleanup()
cache.Set("key", "value")
fmt.Println(cache.Has("key"))
// Output: true
}