add one more example

This commit is contained in:
ahgamut 2022-09-07 09:26:55 +05:30
parent 069ad60349
commit 609e05b0f5
2 changed files with 97 additions and 0 deletions

85
src/bin/example3.rs Normal file
View file

@ -0,0 +1,85 @@
// 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();
}

View file

@ -1,3 +1,15 @@
// This is a comment, and is ignored by the compiler
// You can test this code by clicking the "Run" button over there ->
// or if you prefer to use your keyboard, you can use the "Ctrl + Enter" shortcut
// This code is editable, feel free to hack it!
// You can always return to the original code by clicking the "Reset" button ->
// This is the main function
fn main() {
// Statements here are executed when the compiled binary is called
// Print text to the console
println!("Hello World! This is an APE built with Rust.");
}