music unfamous original game design efficient software wtf
life ui algorithm fix programming

Golang 标准包 flag 使用简单实例

作者:trinity  Golang    2016-8-7  标签:  programming 

最近用到命令行参数,godoc flag 看了一下,和C++ 库 POCO 的处理方式很像,连结构体命名都很相似。做了个Demo,简单到令人发指:

package main

import (
	"flag"
	"fmt"
)

var supported_commands = [...]string{"ip", "port", "auto"}

func init() {
	flag.Int("port", 8080, "listen port")
	flag.String("ip", "192.168.1.100", "listen IP address")
	flag.Bool("auto", true, "start working automatically")
}

func main() {
	flag.Parse()

	for _, cmd := range supported_commands {
		v := flag.Lookup(cmd)
		fmt.Println(v.Name + " " + v.Value.String())
	}
}
 
go build main
go install main
bin/main


ip 192.168.1.100
port 8080
auto true