diff --git a/ownership/Cargo.lock b/ownership/Cargo.lock new file mode 100644 index 0000000..21b71f8 --- /dev/null +++ b/ownership/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "ownership" +version = "0.1.0" diff --git a/ownership/Cargo.toml b/ownership/Cargo.toml new file mode 100644 index 0000000..302f515 --- /dev/null +++ b/ownership/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "ownership" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/ownership/src/main.rs b/ownership/src/main.rs new file mode 100644 index 0000000..da686f6 --- /dev/null +++ b/ownership/src/main.rs @@ -0,0 +1,44 @@ +fn main() { + let s = String::from("hello"); + takes_ownership(s); + let x = 5; + makes_copy(x); + + let s1 = gives_ownership(); + println!("{s1}"); + let s2 = String::from("Hello"); + println!("{s2}"); + let mut s3 = takes_and_gives_back(s2); + println!("{s3}"); + let len = calculate_length(&s3); + println!("{s3} -> {len}"); + change(&mut s3); + println!("{s3}"); + + + +} +fn change(some_string: &mut String){ + some_string.push_str(", world"); +} + +fn takes_ownership(some_string: String) { + println!("{some_string}"); +} + +fn makes_copy(some_integer: i32) { + println!("{some_integer}"); +} + +fn gives_ownership() -> String { + let some_string = String::from("yours"); + some_string +} + +fn takes_and_gives_back(a_string: String) -> String { + a_string +} + +fn calculate_length(s: &String) -> usize { + s.len() +} \ No newline at end of file diff --git a/slices/src/main.rs b/slices/src/main.rs index fad7d98..6a1dca0 100644 --- a/slices/src/main.rs +++ b/slices/src/main.rs @@ -1,27 +1,32 @@ fn main() { - let words = String::from("all string of words"); - println!("{words}"); - let first = find_first(&words); - println!("{first}"); + let my_string = String::from("Hello world"); + + let word = find_first(&my_string[0..6]); + println!("{word}"); + + let word = find_first(&my_string[..]); + println!("{word}"); + + let word = find_first(&my_string); + + println!("{word}"); + + let my_literal_string = "hello world"; + + let word = find_first(&my_literal_string[0..6]); + println!("{word}"); + + let word = find_first(&my_literal_string[..]); + println!("{word}"); + + let word = find_first(&my_literal_string); + + println!("{word}"); - let second = find_first2(&words); - println!("{second}"); } -fn find_first(words: &String) -> String { - let mut word = String::from(""); - for letter in words.chars() { - if letter == ' ' { - break; - } - word.push_str(&letter.to_string()); - } - word -} - - -fn find_first2(words: &str) -> &str { +fn find_first(words: &str) -> &str { let bytes = words.as_bytes(); for (i, &item) in bytes.iter().enumerate() {