Logo

Programming-Idioms

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

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

match str {
    "foo" => foo(),
    "bar" => bar(),
    "baz" => baz(),
    "barfl" => barfl(),
    _ => {}
}
(def whitelist #{#'foo #'bar #'baz #'barfl})
(some-> str symbol resolve whitelist (.call))

str can contain fully qualified function name, like "clojure.string/upper-case".

set #{} is a function of an item: returns it back, if contains it, or nil otherwise.

#' is a literal for var.

some-> takes care of nil checks after each step.

This will throw, if whitelisted var contains not callable (e.g. number) or expects arguments.

New implementation...
< >
tkoenig