diff --git a/ch4/slice_type/Cargo.lock b/ch4/slice_type/Cargo.lock new file mode 100644 index 0000000..cf9dbfd --- /dev/null +++ b/ch4/slice_type/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "slice_type" +version = "0.1.0" diff --git a/ch4/slice_type/Cargo.toml b/ch4/slice_type/Cargo.toml new file mode 100644 index 0000000..50e98a5 --- /dev/null +++ b/ch4/slice_type/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "slice_type" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/ch4/slice_type/src/main.rs b/ch4/slice_type/src/main.rs new file mode 100644 index 0000000..6b93d0a --- /dev/null +++ b/ch4/slice_type/src/main.rs @@ -0,0 +1,54 @@ +// Section 4.4 +// slices allow for reference in contiguous sequences of elements +// inside of a collection. +// +// Part of writing fast Rust code is also understanding how +// allocations work. This portion of the book is important, and I +// need to come back and read it later. + +fn main() { + let mut s = String::from("hello world"); + let word = first_word(&s); + + // borrowed here. Not allowed + // s.clear(); + // print!("word: {word}"); + + // Range syntax. the .. like Haskell + let s = String::from("hello"); + let slice = &s[0..2]; + let slice = &s[..2]; + let slice = &s[..]; // can just slice the whole thing + + // Is this possible? + // no + // let temp_arr_size = 5; + // let temparr = [1; temp_arr_size]; +} + +// This isn't part of the section, just me testing out ownership +fn mod_string(s: &mut String) -> &String { + s.push_str("hello"); + s +} + +fn first_word(s: &String) -> &str { + let bytes = s.as_bytes(); + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + &s[..] +} + +// as.bytes() makes this an immutable reference +// fn example_test() { +// let mut s = String::from("hello"); +// for &item in s.as_bytes().iter() { +// if item == b'l' { +// s.push_str(" world"); +// } +// } +// println!("{s}"); +// }