control flow, primitive types and vectors

This commit is contained in:
2026-01-13 04:19:05 +00:00
parent 505ab3b606
commit 2cd1c84285
19 changed files with 50 additions and 28 deletions

View File

@@ -1,6 +1,6 @@
// TODO: Fix the compiler error in this function.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let vec = vec;
let mut vec = vec;
vec.push(88);

View File

@@ -20,7 +20,7 @@ mod tests {
fn move_semantics2() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
let vec1 = fill_vec(vec0.clone());
assert_eq!(vec0, [22, 44, 66]);
assert_eq!(vec1, [22, 44, 66, 88]);

View File

@@ -1,5 +1,5 @@
// TODO: Fix the compiler error in the function without adding any new line.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec

View File

@@ -10,8 +10,8 @@ mod tests {
fn move_semantics4() {
let mut x = Vec::new();
let y = &mut x;
let z = &mut x;
y.push(42);
let z = &mut x;
z.push(13);
assert_eq!(x, [42, 13]);
}

View File

@@ -4,12 +4,12 @@
// removing references (the character `&`).
// Shouldn't take ownership
fn get_char(data: String) -> char {
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// Should take ownership
fn string_uppercase(mut data: &String) {
fn string_uppercase(mut data: String) {
data = data.to_uppercase();
println!("{data}");
@@ -18,7 +18,7 @@ fn string_uppercase(mut data: &String) {
fn main() {
let data = "Rust is great!".to_string();
get_char(data);
get_char(&data);
string_uppercase(&data);
string_uppercase(data);
}