Simple question

Hello. I'm newbie in Rust. Please help
I have this structure:

	Offer {
		id: "6dc877",
		items: [
			Item {
				id: "ae6ca76dc",
				upd: Some(
					Upd {
						count: Some(
							30,
						),
						deleted: None,
					},
				),
				baseus: None,
			},
		],
	}

when i'm using this:
println!("{:#?}",offer.items[0].upd

I'm getting:
Some( Upd { count: Some( 30, ), deleted: None, }, )

but I need to extract to variable and print value "30" from this.
How to do this?

Since it's possible that offer.items[0].upd and offer.items[0].count could not exist (IE, they're None), you need to match or use something else:

let count = match offer.items[0].upd {
    Some(upd) => match upd.count {
        Some(c) => c,
        _ => -1,
    },
    _ => -1
}

But that -1 funny business isn't idiomatic, instead do:

if let Some(Upd { count: Some(extracted_count), .. }) = &offer.items[0].upd {
    println!("{:?}", extracted_count);
}

Or you could use fancy Option functions:

if let Some(count) = offer
    .items[0]
    .upd
    .as_ref()
    .and_then(|x| x.count.as_ref()) {
    println!("{:?}", count);
}

Thank you so much for detailed response!
Have a good day/night

1 Like