golang中flag包的用法

golang中flag包主要用来CLI下,获取命令参数,示例如下mysql.go:

package main

import (
"flag"
"fmt"
)

func main() {
host := flag.String("h", "localhost", "请指定一个主机")
user := flag.String("u", "root", "请指定数据库用户")
port := flag.Int("P", 3306, "Port number to use for commection or 0 for default to, in port 3306")

//var name string
//flag.StringVar(&name, "u", "root", "请指定用户名") 

flag.Parse() //参数解析

fmt.Println("主机地址:", *host)
fmt.Println("用户名:", *user)
fmt.Println("端口:", *port)
}

像flag.Int、flag.Bool、flag.String这样的函数格式都是一样的,第一个参数表示参数名称,第二个参数表示默认值,第三个参数表示使用说明和描述。flag.StringVar这样的函数第一个参数换成了变量地址,后面的参数和flag.String是一样的。

使用flag来操作命令行参数,支持的格式如下:

-id=1 go run mysql.go -h="127.0.0.1" -u="sxf" -P=3307 
--id=1: go run mysql.go --h="127.0.0.1" --u="sxf" --P=3307 
-id 1:  go run mysql.go -h "127.0.0.1" -u "sxf" 
--id 1:  go run mysql.go --h "127.0.0.1" --u "sxf" --P 3307

还是非常方便的。

这里不指定参数的情况,会使用默认值:

go run mysql.go

 

43 thoughts on “golang中flag包的用法

  1. Pingback: TRX

  2. Pingback: lifestyleinfo.pl/

  3. Pingback: raja qq

  4. Pingback: 토토놀이터

  5. Pingback: other

  6. Pingback: 안전토토사이트

  7. Pingback: circle

  8. Pingback: blog

  9. Pingback: ebenin amini türkce izle

  10. Pingback: พนันบอล

  11. Pingback: ร้อยไหม

  12. Pingback: fun88

  13. Pingback: khong vao duoc 12bet

  14. Pingback: dang nhap w88

  15. Pingback: 바카라

  16. Pingback: หวยเด็ด

  17. Pingback: metal backdrop

  18. Pingback: Azira Torbor

  19. Pingback: istanbul escort

  20. Pingback: 바카라

  21. Pingback: 918kiss

  22. Pingback: Winnipeg furnace Shorty's Plumbing & Heating Inc; Winnipeg HVAC Shorty's Plumbing & Heating Inc

  23. Pingback: Study in Uganda

  24. Pingback: porn

  25. Pingback: Credit Card Applicators Guide

  26. Pingback: hacking software

  27. Pingback: Study in Uganda

  28. Pingback: Online Shopping

  29. Pingback: situs judi slot

  30. Pingback: situs judi online

  31. Pingback: ignou mapc

  32. Pingback: ciprofloxacin 500mg

  33. Pingback: buy chloroquine

  34. Pingback: 안전바카라

  35. Pingback: all models profiles gratis

  36. Pingback: https://www.pinterest.com/ketquaxosotv/

  37. Pingback: course here

  38. Pingback: Tattoo Supplies

  39. Pingback: English To Russian Translation

  40. Pingback: cheap womens wigs

  41. Pingback: nyheter

  42. Pingback: 먹튀검증

  43. Pingback: Coolsculpting

Comments are closed.