Is something like below is possible in rust (returning value of different types in match arms)
fn main() {
let x = 1;
let z = match x{
1 => 0, //return int here
2 => "hello", //return string here
};
println!("{:?}",z); //later use z outside of match statement
}
If you type something as dyn Trait, you can use this thing only as much as the trait allows. If there's some limited number of necessary actions, surely, it's possible.
use std::fmt::Debug;
fn main() {
let x = 1;
let z: Box<dyn Debug> = match x {
1 => Box::new(0), //return int here
2 => Box::new("hello"), //return string here
3 => Box::new(String::from("world")),
_ => unreachable!()
};
println!("{:?}",z); //later use z outside of match statement
}
As said earlier, usually you would use enums. But (extending @2e71828's example) you can also some sort-of dynamic typing in Rust:
use std::any::Any;
fn main() {
let x = 1;
let z: Box<dyn Any> = match x {
1 => Box::new(0),
2 => Box::new("hello"),
3 => Box::new(String::from("world")),
_ => unreachable!()
};
if let Some(i) = z.downcast_ref::<i32>() {
println!("Integer {i}");
}
if let Some(s) = z.downcast_ref::<&str>() {
println!("String slice {s}");
}
if let Some(s) = z.downcast_ref::<String>() {
println!("Owned String {s}");
}
}
I think this is generally pretty bad style though, and I guess there are also some pitfalls when you use downcast. So this example isn't what you usually should do in Rust.