course/flag/flag_type.go

23 lines
720 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"flag"
"fmt"
"time"
)
// flag获取命令行参数
func main() {
//创建一个标志位参数
name := flag.String("name", "wangao", "define name")
age := flag.Int("age", 9000, "define age")
married := flag.Bool("married", false, "define married")
mTime := flag.Duration("mtime", time.Second, "define mTime") //命令行接受的参数需要带单位例如1000h:main.exe -mtime 1000h
//使用flag
flag.Parse()
fmt.Println(*name, *age, *married, mTime)
fmt.Println(flag.Args()) //返回命令行参数后的其他参数,以[]string类型返回
fmt.Println(flag.NArg()) // 返回命令行的其他参数个数
fmt.Println(flag.NFlag()) //返回使用的命令行参数个数
}