Debian Codegraph @

wrapper_sample_test.go

raw
1 // Copyright 2019 Huan Du. All rights reserved.
2 // Licensed under the MIT license that can be found in the LICENSE file.
3
4 package clone
5
6 import "fmt"
7
8 func ExampleWrap() {
9 // Suppose we have a type T defined as following.
10 // type T struct {
11 // Foo int
12 // }
13 v := &T{
14 Foo: 123,
15 }
16 w := Wrap(v).(*T) // Wrap value to protect it.
17
18 // Use w freely. The type of w is the same as that of v.
19
20 // It's OK to modify w. The change will not affect v.
21 w.Foo = 456
22 fmt.Println(w.Foo) // 456
23 fmt.Println(v.Foo) // 123
24
25 // Once we need the original value stored in w, call `Unwrap`.
26 orig := Unwrap(w).(*T)
27 fmt.Println(orig == v) // true
28 fmt.Println(orig.Foo) // 123
29
30 // Or, we can simply undo any change made in w.
31 // Note that `Undo` is significantly slower than `Unwrap`, thus
32 // the latter is always preferred.
33 Undo(w)
34 fmt.Println(w.Foo) // 123
35
36 // Output:
37 // 456
38 // 123
39 // true
40 // 123
41 // 123
42 }