Go by Example: Command-Line Flags

The following example demonstrates how to use command-line flags in Go:

package main

import (

func main() {
	wordPtr := flag.String("word", "default", "a string")
	numPtr := flag.Int("num", 42, "an int")
	boolPtr := flag.Bool("fork", false, "a bool")


	fmt.Println("word:", *wordPtr)
	fmt.Println("num:", *numPtr)
	fmt.Println("fork:", *boolPtr)

When you run the program, you can pass in flags to modify the default values:

$ go run main.go -word=opt -num=7 -fork
word: opt
num: 7
fork: true

The flag.String, flag.Int, and flag.Bool functions create new variables of the specified types, bind them to the flags with the specified names, and assign their addresses to the pointers wordPtr, numPtr, and boolPtr, respectively. The flag.Parse function parses the command-line arguments and sets the declared flags. Finally, the values of the flags are printed out.


Leave a Reply

Your email address will not be published. Required fields are marked *