#Best way to do null in Rust?

12 messages · Page 1 of 1 (latest)

lunar cairn
#

I'm new to Rust - if there is a better way, I'm totally open to it.

I have a statement like this:

struct ... {
    ...
    sell_price: u32
}

But if my item isn't sold yet, there wouldn't be a sell price. I can do a seperate variable (is_sold) and check it... but is there some way to say sell_price = null, and check that it is not null when I want to use it (i.e., if it is null, the item isn't sold yet).

Or is there some better way to do this? This is a personal project, not an assignment, so I'm open to other ways of doing this

inland briar
#

Option::None

drifting ocean
#

Option is the provided way to represent "I have no meaningful value"

#

And can be applied to any other type

heady magnet
#

In which case, the type annotation would be Option<u32>.

lunar cairn
heady magnet
#

That's a module.

lunar cairn
heady magnet
#

That is the enum type, yes.

#

And the enum variant can be represented as just None, because the variants of Option are imported by default, as part of the standard prelude.

lunar cairn
#

Ohh, that makes sense. So this would be right then?

sell_price: Option<u32> = None;
if sell_price.is_none() {
    ...
}
if !sell_price.is_none() {
    ...
}
heady magnet
#

Generally you'd use an if let or match statement instead, to allow you to bind the inner value of the Some variant.