Compare commits

...

2 Commits

Author SHA1 Message Date
Tyrel Souza 1fec9d301d
chapter 4 done 2023-02-26 23:28:16 -05:00
Tyrel Souza 389d2fc0aa
slices 2023-02-26 23:03:42 -05:00
6 changed files with 112 additions and 0 deletions

7
ownership/Cargo.lock generated Normal file
View File

@ -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"

8
ownership/Cargo.toml Normal file
View File

@ -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]

44
ownership/src/main.rs Normal file
View File

@ -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()
}

7
slices/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "slices"
version = "0.1.0"

8
slices/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "slices"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

38
slices/src/main.rs Normal file
View File

@ -0,0 +1,38 @@
fn main() {
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}");
}
fn find_first(words: &str) -> &str {
let bytes = words.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &words[..i];
}
}
&words[..]
}