std-method

Option::map

Transform a present payload while preserving absence. map consumes self; with Option<String> it can transfer the owned String into the closure. For borrowed transformation use as_ref first. Expected stdout (not executed): Some(500) Common mistake: Expecting map to run its closure for None.

Formal Syntax & Structure

rust syntaxrust
fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U

Parameters & Attributes

NameTypeDescription
fFnOnce(T) -> UTransformation for a present value.

Return Value

Option<U>

Transformed payload or None.

Working Example

Example Snippetrust
fn main() {    let grams = Some(250u32);    println!("{:?}", grams.map(|g| g * 2));}
Rust Reference