Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #225 Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

func f(x ...int) {
	if len(x) > 0 {
		println("Present", x[0])
	} else {
		println("Not present")
	}
}

Go does not have optional arguments, but to some extend, they can be mimicked with a variadic parameter.
x is a variadic parameter, which must be the last parameter for the function f.
Strictly speaking, x is a list of integers, which might have more than one element. These additional elements are ignored.
(defn f [& [x]]
  (if (integer? x)
    (println "Present" x)
    (println "Not present")))

Optional argument with positional parameters

New implementation...
< >
tkoenig