1
0
mirror of https://github.com/golang/go synced 2024-11-15 11:20:30 -07:00
go/src/flag/example_textvar_test.go
Joe Tsai 91daaabd56 flag: add TextVar function
The TextVar function makes it easier to integrate the flag package
with any Go type that implements encoding.Text{Marshaler,Unmarshaler}.

Fixes #45754

Change-Id: Id23c37d59cf8c9699a7943a22ce27a45eb685c0f
Reviewed-on: https://go-review.googlesource.com/c/go/+/313329
Trust: Joseph Tsai <joetsai@digital-static.net>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Joseph Tsai <joetsai@digital-static.net>
TryBot-Result: Gopher Robot <gobot@golang.org>
2022-03-10 16:56:17 +00:00

36 lines
847 B
Go

// Copyright 2022 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 (
"flag"
"fmt"
"net"
"os"
)
func ExampleTextVar() {
fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
var ip net.IP
fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse")
fs.Parse([]string{"-ip", "127.0.0.1"})
fmt.Printf("{ip: %v}\n\n", ip)
// 256 is not a valid IPv4 component
ip = nil
fs.Parse([]string{"-ip", "256.0.0.1"})
fmt.Printf("{ip: %v}\n\n", ip)
// Output:
// {ip: 127.0.0.1}
//
// invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1
// Usage of ExampleTextVar:
// -ip IP address
// IP address to parse (default 192.168.0.100)
// {ip: <nil>}
}