GO語言"flag"包中"Value"類型的用法及代碼示例。
值是存儲在標誌中的動態值的接口。 (默認值表示為字符串。)
如果 Value 有一個返回 true 的 IsBoolFlag() bool 方法,則 命令行 解析器使 -name 等效於 -name=true 而不是使用下一個 命令行 參數。
對於存在的每個標誌,按命令行順序調用一次 Set。 flag 包可以調用帶有 zero-valued 接收器的 String 方法,例如 nil 指針。
用法:
type Value interface {
String() string
Set(string) error
}
例子:
package main
import (
"flag"
"fmt"
"net/url"
)
type URLValue struct {
URL *url.URL
}
func (v URLValue) String() string {
if v.URL != nil {
return v.URL.String()
}
return ""
}
func (v URLValue) Set(s string) error {
if u, err := url.Parse(s); err != nil {
return err
} else {
*v.URL = *u
}
return nil
}
var u = &url.URL{}
func main() {
fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
fs.Var(&URLValue{u}, "url", "URL to parse")
fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
}
輸出:
{scheme: "https", host: "golang.org", path: "/pkg/flag/"}
相關用法
- GO Values.Get用法及代碼示例
- GO Values用法及代碼示例
- GO Values.Set用法及代碼示例
- GO Values.Has用法及代碼示例
- GO Values.Del用法及代碼示例
- GO Values.Add用法及代碼示例
- GO Value.FieldByIndex用法及代碼示例
- GO Values.Encode用法及代碼示例
- GO ValidString用法及代碼示例
- GO Valid用法及代碼示例
- GO ValidRune用法及代碼示例
- GO Val用法及代碼示例
- GO Varint用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
- GO NewFromFiles用法及代碼示例
- GO Regexp.FindString用法及代碼示例
- GO Time.Sub用法及代碼示例
- GO Regexp.FindAllIndex用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Value。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。