summaryrefslogtreecommitdiffstats
path: root/src/flag/example_func_test.go
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
commit73df946d56c74384511a194dd01dbe099584fd1a (patch)
treefd0bcea490dd81327ddfbb31e215439672c9a068 /src/flag/example_func_test.go
parentInitial commit. (diff)
downloadgolang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.tar.xz
golang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.zip
Adding upstream version 1.16.10.upstream/1.16.10upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/flag/example_func_test.go')
-rw-r--r--src/flag/example_func_test.go41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/flag/example_func_test.go b/src/flag/example_func_test.go
new file mode 100644
index 0000000..7c30c5e
--- /dev/null
+++ b/src/flag/example_func_test.go
@@ -0,0 +1,41 @@
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package flag_test
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "net"
+ "os"
+)
+
+func ExampleFunc() {
+ fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError)
+ fs.SetOutput(os.Stdout)
+ var ip net.IP
+ fs.Func("ip", "`IP address` to parse", func(s string) error {
+ ip = net.ParseIP(s)
+ if ip == nil {
+ return errors.New("could not parse IP")
+ }
+ return nil
+ })
+ fs.Parse([]string{"-ip", "127.0.0.1"})
+ fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+ // 256 is not a valid IPv4 component
+ fs.Parse([]string{"-ip", "256.0.0.1"})
+ fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+ // Output:
+ // {ip: 127.0.0.1, loopback: true}
+ //
+ // invalid value "256.0.0.1" for flag -ip: could not parse IP
+ // Usage of ExampleFunc:
+ // -ip IP address
+ // IP address to parse
+ // {ip: <nil>, loopback: false}
+}