diff options
Diffstat (limited to 'rust/theBook/chapter-4-understanding-ownership')
-rw-r--r-- | rust/theBook/chapter-4-understanding-ownership/emp1.rs | 9 | ||||
-rw-r--r-- | rust/theBook/chapter-4-understanding-ownership/emp2.rs | 11 | ||||
-rw-r--r-- | rust/theBook/chapter-4-understanding-ownership/str.rs | 38 |
3 files changed, 58 insertions, 0 deletions
diff --git a/rust/theBook/chapter-4-understanding-ownership/emp1.rs b/rust/theBook/chapter-4-understanding-ownership/emp1.rs new file mode 100644 index 0000000..a0f4bbd --- /dev/null +++ b/rust/theBook/chapter-4-understanding-ownership/emp1.rs @@ -0,0 +1,9 @@ +fn main() { + let mut s = String::from("hello"); + + let r1 = &s; + let r2 = &s; + println!("{},{}",r1,r2); + let r3 = &mut s; + println!("{r3}"); +} diff --git a/rust/theBook/chapter-4-understanding-ownership/emp2.rs b/rust/theBook/chapter-4-understanding-ownership/emp2.rs new file mode 100644 index 0000000..02a24b0 --- /dev/null +++ b/rust/theBook/chapter-4-understanding-ownership/emp2.rs @@ -0,0 +1,11 @@ +fn main() { + let str = dangle(); + + println!("{str}"); +} + +fn dangle() -> &String { + let s = String::from("Hello"); + + &s +} diff --git a/rust/theBook/chapter-4-understanding-ownership/str.rs b/rust/theBook/chapter-4-understanding-ownership/str.rs new file mode 100644 index 0000000..09bab67 --- /dev/null +++ b/rust/theBook/chapter-4-understanding-ownership/str.rs @@ -0,0 +1,38 @@ +fn first_word(s: &String) -> usize { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return i; + } + } + + s.len() +} + +fn second_word(s: &str) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[0..s.len()] +} + +fn main() { + let mut s = String::from("hello world"); + + let word = first_word(&s); + + println!("{word}"); + + println!("{}",&s[0..5]); + + let word2 = second_word(&s[..]); + + println!("{}",&word2); + s.clear(); +} |