finish ch4, come back later
This commit is contained in:
parent
aa3e08fcfb
commit
1008a76306
7
ch4/slice_type/Cargo.lock
generated
Normal file
7
ch4/slice_type/Cargo.lock
generated
Normal file
@ -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"
|
6
ch4/slice_type/Cargo.toml
Normal file
6
ch4/slice_type/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "slice_type"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
54
ch4/slice_type/src/main.rs
Normal file
54
ch4/slice_type/src/main.rs
Normal file
@ -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}");
|
||||
// }
|
Loading…
x
Reference in New Issue
Block a user