Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions exercises/ownership-borrowing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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
Expand All @@ -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;
}
Expand All @@ -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
Expand All @@ -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
}
};

Expand All @@ -82,34 +83,34 @@ 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();
}
}
}

// Exercise 7
// Make it compile
fn exercise7() {
let mut v: Vec<&str> = Vec::new();
let mut v: Vec<String> = 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);
}

// Exercise 8
// Make it compile
fn exercise8() {
let mut accounting = vec!["Alice", "Ben"];
let mut accounting: Vec<String> = vec!["Alice".to_string(), "Ben".to_string()];

loop {
let mut add_input = String::from("");
Expand All @@ -126,6 +127,6 @@ fn exercise8() {
}

let person = add_vec[0];
accounting.push(person);
accounting.push(person.to_string());
}
}