-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc_test.go
84 lines (63 loc) · 1.42 KB
/
func_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
package flagx_test
import (
"encoding/hex"
"flag"
"fmt"
"math/rand"
"github.com/dolmen-go/flagx"
)
func ExampleFunc() {
flags := flag.NewFlagSet("test", flag.PanicOnError) // Usually flag.CommandLine
var all []string
push := func(s string) error {
all = append(all, s)
return nil
}
// A flag that apppends the given value to slice all
flags.Var(
flagx.Func(push),
"push", "push `value`",
)
flags.Parse([]string{"-push=a", "-push=b"})
fmt.Println(all)
// Output:
// [a b]
}
// Shows an hex encoded parameter
func ExampleFunc_hex() {
flags := flag.NewFlagSet("test", flag.PanicOnError) // Usually flag.CommandLine
// Destination of the decoded parameter value
var bin []byte
// A flag that decodes value from hexadecimal
flags.Var(
flagx.Func(func(s string) (err error) {
bin, err = hex.DecodeString(s)
return
}),
"hex", "hex encoded `value`",
)
flags.Parse([]string{"-hex=68656c6c6f"})
fmt.Printf("%q", bin)
// Output:
// "hello"
}
func ExampleBoolFunc() {
flags := flag.NewFlagSet("test", flag.PanicOnError) // Usually flag.CommandLine
var n int
// A flag that set the value of n
flags.IntVar(&n, "value", 0, "set given value")
// A flag that set n to a random value
flags.Var(
flagx.BoolFunc(
func(b bool) error {
n = rand.Int()
return nil
},
),
"rand", "set random value",
)
flags.Parse([]string{"-rand", "-value=5"})
fmt.Println(n)
// Output:
// 5
}