Skip to content

Commit ea10c27

Browse files
committed
flag: add Func
Refs golang#39557
1 parent a295d59 commit ea10c27

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/flag/example_value_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,19 @@ func ExampleValue() {
4242
// Output:
4343
// {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
4444
}
45+
46+
func ExampleFunc() {
47+
fs := flag.NewFlagSet("ExampleFunc", flag.ExitOnError)
48+
var u *url.URL
49+
fs.Func("url", "`URL` to parse", func(s string) error {
50+
var err error
51+
u, err = url.Parse(s)
52+
return err
53+
})
54+
55+
fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
56+
fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
57+
58+
// Output:
59+
// {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
60+
}

src/flag/flag.go

+18
Original file line numberDiff line numberDiff line change
@@ -1043,3 +1043,21 @@ func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
10431043
f.name = name
10441044
f.errorHandling = errorHandling
10451045
}
1046+
1047+
// Func defines a flag with the specified name and usage string.
1048+
// TODO: more here
1049+
func (f *FlagSet) Func(name, usage string, cb func(string) error) {
1050+
f.Var(cbfunc(cb), name, usage)
1051+
}
1052+
1053+
// Func defines a flag with specified name, default value, and usage string.
1054+
// TODO: more here
1055+
func Func(name, usage string, f func(string) error) {
1056+
CommandLine.Func(name, usage, f)
1057+
}
1058+
1059+
type cbfunc func(string) error
1060+
1061+
func (f cbfunc) Set(s string) error { return f(s) }
1062+
1063+
func (f cbfunc) String() string { return "" }

0 commit comments

Comments
 (0)