Rust learning: lessons, notes, and exercise crates

This commit is contained in:
2026-09-06 23:59:08 +07:00
commit 6ddf41aa81
119 changed files with 10873 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/target
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ownership"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "ownership"
version = "0.1.0"
edition = "2024"
[dependencies]
+71
View File
@@ -0,0 +1,71 @@
fn main() {
let mut s = String::from("hello");
s.push_str(", world");
let x = calculate_length(&s);
println!("{s} with len {x}");
let y = "lksadjflksajdfc";
println!("{y}");
// {
// let x = 12;
// }
// println!("{x}");
{
let s1 = String::from("hello");
let s2 = s1;
println!("{s2}, world!");
}
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here
let x = 5; // x comes into scope
makes_copy(x); // Because i32 implements the Copy trait,
// x does NOT move into the function,
// so it's okay to use x afterward.
let mut s = String::from("hello");
{
let r1 = &mut s;
println!("{r1}");
let x = r1.len();
println!("{x}");
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &mut s;
}
fn takes_ownership(some_string: String) {
// some_string comes into scope
println!("{some_string}");
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) {
// some_integer comes into scope
println!("{some_integer}");
} // Here, some_integer goes out of scope. Nothing special happens.
fn calculate_length(s: &String) -> usize {
s.len()
}
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}