Skip to content

Instantly share code, notes, and snippets.

@hahwul
Created February 13, 2021 14:36
Show Gist options
  • Save hahwul/b3870d58fd038afba05099ee9be86417 to your computer and use it in GitHub Desktop.
Save hahwul/b3870d58fd038afba05099ee9be86417 to your computer and use it in GitHub Desktop.
Golang custom flag usage
package main
import (
"flag"
"fmt"
)
func main() {
flag.String("a", "", "flag 1")
flag.String("b", "", "flag 2")
flag.String("c", "", "flag 3")
flag.Usage = func() {
flagSet := flag.CommandLine
fmt.Printf("Usage of %s:\n", "./tool")
order := []string{"a", "b", "c"}
for _, name := range order {
flag := flagSet.Lookup(name)
fmt.Printf("-%s\t%s\n", flag.Name,flag.Usage)
}
}
flag.Parse()
}
/*
[ output ]
Usage of ./tool:
-a flag 1
-b flag 2
-c flag 3
*/
@w0ltage
Copy link

w0ltage commented Jun 10, 2023

works like a charm, thanks!

@Kif11
Copy link

Kif11 commented Oct 16, 2024

What is the difference between this and flag.PrintDefaults()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment