实现说明
整个示例围绕函数 String、Set、main组织。
使用要点
- 演示输出是带标签的(
port:、tags:、count:),每个操作都会留下自己的一行标注。 - 运行整个文件:
main会依次驱动String。
常见问题
运行「flag.Var 注册自定义 Value 类型」会打印什么?
运行文件本身,port:、tags:、count: 这些前缀各对应一段演示逻辑。
入口签名:func (r *repeatable) String() string
核心语句
return errors.New("tag must not be empty")
func (r *repeatable) String() string {
return strings.Join(*r, ",")
}
代码示例
package main
import (
"errors"
"flag"
"fmt"
"strings"
)
// repeatable implements flag.Value: Set handles each -tag occurrence, String renders the value
type repeatable []string
func (r *repeatable) String() string {
return strings.Join(*r, ",")
}
func (r *repeatable) Set(value string) error {
if value == "" {
return errors.New("tag must not be empty")
}
*r = append(*r, value)
return nil
}
func main() {
fs := flag.NewFlagSet("deploy", flag.ContinueOnError)
var tags repeatable
fs.Var(&tags, "tag", "repeatable label, may be given multiple times")
port := fs.Int("port", 8080, "listen port")
// Same -tag twice: Set accumulates both into one slice
if err := fs.Parse([]string{"-tag", "web", "-port", "9090", "-tag", "edge"}); err != nil {
panic(err)
}
fmt.Println("port:", *port)
fmt.Println("tags:", tags.String())
fmt.Println("count:", len(tags))
// Empty value rejected by Set: the flag package surfaces that error to the caller
fmt.Println("empty rejected:", fs.Parse([]string{"-tag", ""}) != nil)
}