Understanding the use of underscore (_)

Underscore is a special character in Odin that enables us to ignore something.

For example if the function has @(require_results).

We can ignore the result.

@(require_results)
foo :: proc() -> bool {
    return true
}

@(require_results)
bar :: proc() -> bool, int {
    return true, 2
}

main :: proc() {
    foo() // won't compile
    _ = foo() // Ok
    _, _ = bar() // Ok
}

Also can be used inside switch statements if we don’t need the variable.

Foo :: union {int, bool}
f: Foo = 123

#partial switch _ in f {
   case bool: fmt.println("bool")
}

Also it can be used like this:

import "base:runtime"
_ :: runtime

@Barinzaya explains:

Normally, that would be used to force the right side (runtime in this case) to be considered as used, to prevent errors from unused imports (when compiling with -vet ). You’d normally do that for an import when you want to import something but only conditionally use it (e.g. in a when block) or use it only for side effects. Same idea as doing _ := some_proc() if some_proc requires its results be used, but you want to ignore them anyway.

3 Likes

I like calling it “the black hole variable”. Because it sucks

…err i mean it sucks out the values so that they never come back, or something, I can’t word it properly

1 Like