How to use multiple return values when some are initialized and some are not

I am trying to do something like this

package main

Foo :: union {
	int,
	string,
}

main :: proc() {
	a: int
	foo: Foo = 5

	a, ok := foo.(int)
}

and get the following error;

din run -file main.odin
/private/tmp/main.odin(12:2) Error: Redeclaration of 'a' in this scope
        at /private/tmp/main.odin(9:2)
        a, ok := foo.(int)
        ^

so I try it the other way around;

package main

Foo :: union {
	int,
	string,
}

main :: proc() {
	a: int
	foo: Foo = 5

	a, ok = foo.(int)
}

and get the following error

odin run -file main.odin
/private/tmp/main.odin(12:5) Error: Undeclared name: ok
        a, ok = foo.(int)
           ^^

is there a simpler way to do this where I do not have to explicitly initialize ok. as it will get annoying to do so

Why not the following?

main :: proc() {
	a: int
	foo: Foo = 5

	ok: bool
	a, ok = foo.(int)
}

I understand that separating the declaration and initialization of ok feels a bit clunky. But adding an Odin feature to make this more ergonomic may actually make it more complicated and make the code harder to reason about. Take for example how Go lang handles the error variables:

Reddit - Why is err a new variable in second assignment, and an old one in third one?


Also, instead of the name ok, you could name it like ok_foo or ok_foo_int. This is useful when you need to use the name ok for several different types of errors in the same scope.

Also, see the following Discussion:

When checking multiple ok values in the same scope, I prefer giving them unique names (e.g., ok, ok2) so I can keep using :=. Other approaches feel a bit too verbose for my liking.

some_val, ok := some_proc()
if !ok // handle the error
another_val, ok2 := some_proc_2()
if !ok2 // handle the error

But if I don’t want to log anything and just return early with default value if !ok then I use or_return

some_val := some_proc() or_return

I would do it like that

package main

Foo :: union {
	int,
	string,
}

main :: proc() {
	foo := Foo(5)
	a, ok := foo.(int)
	if !ok {
		// handle !ok
	}
}