diff options
Diffstat (limited to 'rust/compound.rs')
| -rw-r--r-- | rust/compound.rs | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/rust/compound.rs b/rust/compound.rs new file mode 100644 index 0000000..5a8114f --- /dev/null +++ b/rust/compound.rs @@ -0,0 +1,67 @@ +// Compound types +// +// Types composed of another types + +// String vs &str +// String - string slices + +// String: heap allocated string type - NOT NULL TERMINATED +// (ptr, len, capacity) +// &str: immutable sequence of UTF-8 bytes in memory +// (ptr, len) +// &str - more lightweight and efficient +// +// String Literal: compile time known sequence of UTF-8 bytes + +fn main() { + let s = String::from("Howdy partner"); + + let hello: &str = &s[0..5]; + let world: &str = &s[6..13]; + +// Wow, suuuper safe +// let world: &str = &s[6..14]; + + println!("{} {}", hello, world); + compound(); + string_playground(); + concatenate(); +} + +fn compound() { + let s: Box<str> = "Howdy partner".into(); + greetings(&s); + + // We could also just not use a box here and create a slice. + // let s: &str = "Howdy partner"; + // greetings(s); +} + +fn greetings(s: &str) { + println!("{}", s); +} + +fn string_playground() { + let mut s = String::from(""); + s.push_str("hello, world"); + s.push('!'); + + println!("Success"); +} + +fn concatenate() { + let s1: String = String::from("howdy,"); + let s2: String = String::from("partner"); + + // you can concatenate a String + &str but you can't concatenate 2 Strings + // This consumes the string, and the ownership of s1 is transferred to s3 + // This likely just push s2 into s1. + + // Two ways of converting s2 to str: + // using .as_str() method +// let s3: String = s1 + s2.as_str(); + // passing a reference to &s2 + let s3: String = s1 + &s2; + + println!("{}", s3); +} |
