diff --git a/exercises/ownership-borrowing/src/lib.rs b/exercises/ownership-borrowing/src/lib.rs index 46ccf53c..c827f3a3 100644 --- a/exercises/ownership-borrowing/src/lib.rs +++ b/exercises/ownership-borrowing/src/lib.rs @@ -3,7 +3,7 @@ fn exercise1() { // Use as many approaches as you can to make it work let x = String::from("hello, world"); - let y = x; + let y = &x; let z = x; } @@ -17,8 +17,9 @@ fn exercise2() { println!("{}", s2); } // Only modify the code below! -fn take_ownership(s: String) { - println!("{}", s); +fn take_ownership(s: String) -> String { + // println!("{}", s); + s } // Exercise 3 @@ -41,7 +42,7 @@ fn exercise3() { let mut addition: f64 = 0.0; // Sumar valores en additions - for element_index in additions { + for element_index in 0..additions.len() { let addition_aux = values[element_index]; addition = addition_aux + addition; } @@ -50,10 +51,10 @@ fn exercise3() { // Exercise 4 // Make it compile -fn exercise4(value: u32) -> &'static str { +fn exercise4(value: u32) -> String { let str_value = value.to_string(); // Convert u32 to String let str_ref: &str = &str_value; // Obtain a reference to the String - str_ref // Return the reference to the String + str_value // Return the reference to the String } // Exercise 5 @@ -69,7 +70,7 @@ fn exercise5() { None => { let value = "3.0".to_string(); my_map.insert(key, value); - &value // HERE IT FAILS + &my_map[&key] // HERE IT FAILS } }; @@ -82,14 +83,14 @@ fn exercise5() { use std::io; fn exercise6() { - let mut prev_key: &str = ""; + let mut prev_key: String = String::from(""); for line in io::stdin().lines() { let s = line.unwrap(); let data: Vec<&str> = s.split("\t").collect(); if prev_key.len() == 0 { - prev_key = data[0]; + prev_key = data[0].to_string(); } } } @@ -97,11 +98,11 @@ fn exercise6() { // Exercise 7 // Make it compile fn exercise7() { - let mut v: Vec<&str> = Vec::new(); + let mut v: Vec = Vec::new(); { let chars = [b'x', b'y', b'z']; - let s: &str = std::str::from_utf8(&chars).unwrap(); - v.push(&s); + let s = std::str::from_utf8(&chars).unwrap(); + v.push(s.to_string()); } println!("{:?}", v); } @@ -109,7 +110,7 @@ fn exercise7() { // Exercise 8 // Make it compile fn exercise8() { - let mut accounting = vec!["Alice", "Ben"]; + let mut accounting: Vec = vec!["Alice".to_string(), "Ben".to_string()]; loop { let mut add_input = String::from(""); @@ -126,6 +127,6 @@ fn exercise8() { } let person = add_vec[0]; - accounting.push(person); + accounting.push(person.to_string()); } }