Logo

Programming-Idioms

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

Idiom #267 Pass string to argument that can be of any type

Declare an argument x to a procedure foo that can be of any type. If the type of the argument is a string, print it, otherwise print "Nothing."

Test by passing "Hello, world!" and 42 to the procedure.

import "fmt"
func foo(x any) {
	if s, ok := x.(string); ok {
		fmt.Println(s)
	} else {
		fmt.Println("Nothing.")
	}
}

func main() {
	foo("Hello, world!")
	foo(42)
}

An argument of type any may receive a value of any type.
We convert it with a type assertion.
(defn foo [x]
  (println (if (string? x) x "Nothing.")))

(foo "Hello, world!")
(foo 42)

New implementation...
< >
tkoenig