summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-4-understanding-ownership
diff options
context:
space:
mode:
authorgarhve <git@garhve.com>2022-12-26 16:52:29 +0800
committergarhve <git@garhve.com>2022-12-26 16:52:29 +0800
commit3172b239863e1151d85197fdb4ea3e42d421256e (patch)
tree81e4eb4eb06725f17188bf85d9cd7305eceedab3 /rust/theBook/chapter-4-understanding-ownership
parent1dece36fd7e315aee98f1c06d7064fbd6ef877e8 (diff)
finish chapter 5
Diffstat (limited to 'rust/theBook/chapter-4-understanding-ownership')
-rw-r--r--rust/theBook/chapter-4-understanding-ownership/emp1.rs9
-rw-r--r--rust/theBook/chapter-4-understanding-ownership/emp2.rs11
-rw-r--r--rust/theBook/chapter-4-understanding-ownership/str.rs38
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();
+}