added more strings and todos

This commit is contained in:
2026-04-25 12:56:58 -04:00
committed by edgul
parent 0c9a7ec030
commit 04e561d04e
+38 -2
View File
@@ -1,3 +1,4 @@
use std::rc::Rc;
// when a String is passed to this function a move occurs: // when a String is passed to this function a move occurs:
// BUT only the stack allocation (ptr, len, cap) is copied over // BUT only the stack allocation (ptr, len, cap) is copied over
@@ -10,6 +11,8 @@ fn takes_string(_s: String) {
} }
// You can do this, but you probably want &str
// UNLESS you want `&mut String`
#[allow(dead_code)] #[allow(dead_code)]
fn takes_string_ref(_s: &String) { fn takes_string_ref(_s: &String) {
@@ -42,6 +45,12 @@ fn _get_static_str() -> &'static str {
"hello" "hello"
} }
// The #[cfg(test)] annotation on the tests module tells Rust to compile
// and run the test code only when you run cargo test, not when you run cargo build
#[cfg(test)]
mod tests {
use super::*; // need access to functions above
#[test] #[test]
fn test_string() { fn test_string() {
let s = String::new(); // no heap allocation until we add characters (capacity > 0) let s = String::new(); // no heap allocation until we add characters (capacity > 0)
@@ -78,6 +87,33 @@ fn test_string() {
let _s5 = String::from("literal is copied to heap"); // data copied to heap let _s5 = String::from("literal is copied to heap"); // data copied to heap
let _s6 = String::from(s_lit); //underlying data copied to heap let _s6 = String::from(s_lit); //underlying data copied to heap
// todo: Cow // Box<str> is owned, heap allocated, fixed size, immutable
} // where as `&str` is borrowed view, linked to source, immutable
// both have (ptr, len) -> underlying mem
let _s7 : Box<str> = "hello".into();
// Rc<str> (single-threaded reference counting)
// HEAP memory layout:
// * counter (strong)
// * counter (weak)
// * len
// * data
// STACK memory:
// * ptr
// * len
//
// Why are there two lengths?
let rc_str : Rc<str> = Rc::from("rc_str");
// let rc_str2 : Rc<str> = rc_str; // this moves
let rc_str2 : Rc<str> = rc_str.clone(); // copy ptr, increment counter
println!("printing {}", rc_str);
println!("printing {}", rc_str);
println!("printing {}", rc_str2);
// todo: Arc<str>
// todo: Cow
// todo: byte strings: &[u8] and Vec<u8>
// todo: Os & platform strings: OsStr & OsString, Path & PathBuf
// todo: ffi strings: CString & CStr
}
}