Movatterモバイル変換


[0]ホーム

URL:


let

Keywordlet 

Source
Expand description

Bind a value to a variable.

The primary use for thelet keyword is inlet statements, which are used to introduce a newset of variables into the current scope, as given by a pattern.

letthing1: i32 =100;letthing2 =200+ thing1;letmutchanging_thing =true;changing_thing =false;let(part1, part2) = ("first","second");structExample {    a: bool,    b: u64,}letExample { a, b:_} = Example {    a:true,    b:10004,};assert!(a);

The pattern is most commonly a single variable, which means no pattern matching is done andthe expression given is bound to the variable. Apart from that, patterns used inlet bindingscan be as complicated as needed, given that the pattern is exhaustive. See theRustbook for more information on pattern matching. The type of the pattern is optionallygiven afterwards, but if left blank is automatically inferred by the compiler if possible.

Variables in Rust are immutable by default, and require themut keyword to be made mutable.

Multiple variables can be defined with the same name, known as shadowing. This doesn’t affectthe original variable in any way beyond being unable to directly access it beyond the point ofshadowing. It continues to remain in scope, getting dropped only when it falls out of scope.Shadowed variables don’t need to have the same type as the variables shadowing them.

letshadowing_example =true;letshadowing_example =123.4;letshadowing_example = shadowing_exampleasu32;letmutshadowing_example =format!("cool! {shadowing_example}");shadowing_example +=" something else!";// not shadowing

Other places thelet keyword is used include along withif, in the form ofif letexpressions. They’re useful if the pattern being matched isn’t exhaustive, such as withenumerations.while let also exists, which runs a loop with a pattern matched value untilthat pattern can’t be matched.

For more information on thelet keyword, see theRust book or theReference


[8]ページ先頭

©2009-2026 Movatter.jp