I have a function that returns one of two structs dependings on some logic. I need to specify the return type to be one of two. How do I do that?
struct A {}
struct B {}
fn picky() -> ??? {
let a = A{};
let b = B{};
if 1 < 10 {
a
} else {
b
}
}
fn main() {
picky();
}
This feels like it should be trivial but after hours on Google I still can't figure it out.
Your function has only one return type, but this type may be an enum:
struct A {}
struct B {}
enum AB {
A(A),
B(B),
}
fn picky() -> AB {
let a = A{};
let b = B{};
if 1 < 10 {
AB::A(a)
} else {
AB::B(b)
}
}
That's exactly how Result
works in Rust: you get either the desired value or an error, because the result is an enum with two variants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With