Last active
November 5, 2019 08:17
-
-
Save kjk/31b5364c35801027a2929b17e9155425 to your computer and use it in GitHub Desktop.
command line arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// :run go run main.go -echo echo-arg additional arg | |
// :collection Essential Go | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
) | |
// :show start | |
var ( | |
flgHelp bool | |
flgEcho string | |
) | |
func parseCmdLineFlags() { | |
flag.BoolVar(&flgHelp, "help", false, "if true, show help") | |
flag.StringVar(&flgEcho, "echo", "", "") | |
flag.Parse() | |
} | |
func main() { | |
parseCmdLineFlags() | |
if flgHelp { | |
flag.Usage() | |
os.Exit(0) | |
} | |
fmt.Printf("flag -echo: '%s'\n", flgEcho) | |
remainingArgs := flag.Args() | |
for _, arg := range remainingArgs { | |
fmt.Printf("Remainig arg: '%s'\n", arg) | |
} | |
} | |
// :show end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment