rust-ape-example/src/bin/example3.rs
2022-09-07 09:26:55 +05:30

86 lines
2.3 KiB
Rust

// https://doc.rust-lang.org/rust-by-example/variable_bindings.html
fn example3a() {
let an_integer = 1u32;
let a_boolean = true;
let unit = ();
// copy `an_integer` into `copied_integer`
let copied_integer = an_integer;
println!("An integer: {:?}", copied_integer);
println!("A boolean: {:?}", a_boolean);
println!("Meet the unit value: {:?}", unit);
// The compiler warns about unused variable bindings; these warnings can
// be silenced by prefixing the variable name with an underscore
let _unused_variable = 3u32;
let noisy_unused_variable = 2u32;
// FIXME ^ Prefix with an underscore to suppress the warning
// Please note that warnings may not be shown in a browser
}
// https://doc.rust-lang.org/rust-by-example/variable_bindings/mut.html
fn example3b() {
let _immutable_binding = 1;
let mut mutable_binding = 1;
println!("Before mutation: {}", mutable_binding);
// Ok
mutable_binding += 1;
println!("After mutation: {}", mutable_binding);
// Error!
// _immutable_binding += 1;
// FIXME ^ Comment out this line
}
// https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html
fn example3c() {
// This binding lives in the main function
let long_lived_binding = 1;
// This is a block, and has a smaller scope than the main function
{
// This binding only exists in this block
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
}
// End of the block
// Error! `short_lived_binding` doesn't exist in this scope
// println!("outer short: {}", short_lived_binding);
// FIXME ^ Comment out this line
println!("outer long: {}", long_lived_binding);
}
// https://doc.rust-lang.org/rust-by-example/variable_bindings/freeze.html
fn example3d() {
let mut _mutable_integer = 7i32;
{
// Shadowing by immutable `_mutable_integer`
let _mutable_integer = _mutable_integer;
// Error! `_mutable_integer` is frozen in this scope
// _mutable_integer = 50;
// FIXME ^ Comment out this line
// `_mutable_integer` goes out of scope
}
// Ok! `_mutable_integer` is not frozen in this scope
_mutable_integer = 3;
}
pub fn main() {
example3a();
example3b();
example3c();
example3d();
}