Hmmm seems like there may be some compiler limitations around using ConditionalType as a return type. This is the only way I could get this to work right now.
Thanks Brian, that does seem to be the best possible option for now.
In my project, I’ve decided to switch back to 2 separate methods for now - switching to nightly results in compatibility issues with def raises and third party libraries (EmberJson). But it is good to know for future reference.
For the Mojo team: Would it be possible to enable the more intuitive syntax like I started with above?
To vary the return type of a function you can just use a parameter for the actual return type.
Then inside the function assign to the parameterised return type using rebind so that the assignment of a concrete type to the parameterised return type works (the types are different names but boil down to the same type).
The following works in mojo, put it into test_return.mojo file:
from std.sys.intrinsics import _type_is_eq
from std.testing import TestSuite
def do_stuff[R: AnyType & ImplicitlyCopyable]() raises -> R:
var result: R
comptime
if _type_is_eq[R, Int]():
print("R is Int")
var r = Int(42)
result = rebind[R](r)
elif _type_is_eq[R, Float64]():
print("R is Float64")
var r = Float64(3.14)
result = rebind[R](r)
elif _type_is_eq[R, NoneType]():
print("R is NoneType")
var r = None
result = rebind[R](r)
else:
raise Error("Return type must be Int, Float64 or NoneType")
return result
def test_stuff() raises:
print("Int", do_stuff[Int]())
print("Float64", do_stuff[Float64]())
print("None", do_stuff[NoneType]())
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()