chapter 4 done

This commit is contained in:
Tyrel Souza 2023-02-26 23:28:16 -05:00
parent 389d2fc0aa
commit 1fec9d301d
No known key found for this signature in database
GPG Key ID: F3614B02ACBE438E
4 changed files with 83 additions and 19 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()
}

View File

@ -1,27 +1,32 @@
fn main() { fn main() {
let words = String::from("all string of words"); let my_string = String::from("Hello world");
println!("{words}");
let first = find_first(&words); let word = find_first(&my_string[0..6]);
println!("{first}"); 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 { fn find_first(words: &str) -> &str {
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 {
let bytes = words.as_bytes(); let bytes = words.as_bytes();
for (i, &item) in bytes.iter().enumerate() { for (i, &item) in bytes.iter().enumerate() {