I have a variable (Box<Any>
) and a struct Null
. I want to match that variable to check if it is Null
.
I want to do something like this:
struct Null;
fn main() {
let mybox = Box::new("Box");
match (mybox, Box::new(Null {}))
{
(Box(Null), Box(Null)) => println!("It is Null"),
_ => println!("It is not Null")
}
}
You need to have a look at the Option type. What you want is Option<Box<T>>
.
Then you can use match to match against Some or None. See the TRPL and/or the Rust Docs for the Option type.
3 Likes
kornel
August 20, 2019, 6:10pm
3
It doesn't work with match
like that. You'd have to use downcast_ref
, BUT the whole design is very suspicious and un-Rust-like.
Try approaching the problem differently, without the weird Null
thing. Perhaps you need an enum
? Or Option<Box<SpecificType>>
?
Is it possible to match and do nothing if it is None, but do something if it is not?
That looks like a code smell! Your Null
is a zero sized type and Option
is the best alternative. Just for pedagogy, see the playground .
The Option<Box<TheType>>
works with the match, but when I try to the value, I get Some(TheType)
?
You can extract the contents of a Some
with an if let
:
let my_box = Some(Box::new("Box"));
if let Some(x) = my_box {
// x is Box containing "Box"
}
This works on a match as well, but if you just need to handle the case where there's some value it's simpler.
let my_box = Some(Box::new("Box"));
if let Some(x) = my_box {
// x is Box containing "Box"
}
I only get TheType
when I try to print it
Can you post your full code to the playground ? What specifically are you printing? What is TheType
?
system
Closed
November 18, 2019, 7:02pm
10
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.