Check if Flag Was Provided in Go

Use the flag.Visit()

Description: Visit visits the command-line flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

use:

func isFlagPassed(name string) bool {
    found := false
    flag.Visit(func(f *flag.Flag) {
        if f.Name == name {
            found = true
        }
    })
    return found
}

The built-in flag types don't support distinguishing default values and explicit assignment to the default value. However, the flag package is quite flexible, and allows you to roll your own type that does, using the flag.Value interface.

Here's a full example that contains a string flag which records if it's been assigned to.

package main

import (
    "flag"
    "fmt"
)

type stringFlag struct {
    set   bool
    value string
}

func (sf *stringFlag) Set(x string) error {
    sf.value = x
    sf.set = true
    return nil
}

func (sf *stringFlag) String() string {
    return sf.value
}

var filename stringFlag

func init() {
    flag.Var(&filename, "filename", "the filename")
}

func main() {
    flag.Parse()
    if !filename.set {
        fmt.Println("--filename not set")
    } else {
        fmt.Printf("--filename set to %q\n", filename.value)
    }
}

Here's some example runs:

$ go run a.go -filename=abc
--filename set to "abc"

$ go run a.go -filename=
--filename set to ""

$ go run a.go
--filename not set