summaryrefslogtreecommitdiff
path: root/lifetimes/src/main.rs
diff options
context:
space:
mode:
author53hornet <53hornet@gmail.com>2019-02-25 21:15:40 -0500
committer53hornet <53hornet@gmail.com>2019-02-25 21:15:40 -0500
commitb7dd584bca69dc729d77b11b6a8378b8be0af647 (patch)
treee9460283f474d53961bddefb2e684f9b20516c74 /lifetimes/src/main.rs
parenta0070916ef13387461a11bb26d5c798b07121165 (diff)
downloadlearning-rust-b7dd584bca69dc729d77b11b6a8378b8be0af647.tar.xz
learning-rust-b7dd584bca69dc729d77b11b6a8378b8be0af647.zip
Added lifetimes; split code into library for minigrep.
Diffstat (limited to 'lifetimes/src/main.rs')
-rw-r--r--lifetimes/src/main.rs43
1 files changed, 43 insertions, 0 deletions
diff --git a/lifetimes/src/main.rs b/lifetimes/src/main.rs
new file mode 100644
index 0000000..87b6ce6
--- /dev/null
+++ b/lifetimes/src/main.rs
@@ -0,0 +1,43 @@
+fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
+ // what this is doing is basically tagging x and y and the
+ // result with the same 'a, telling rust not to let any
+ // of them expire before the others; that way nothing
+ // will go out of scope prematurely and the result will
+ // always have a non-null reference
+
+ // basically, 'a gives all three values the same lifetime.
+ // so long as they're all alive at the same time, there are
+ // no reference errors
+
+ // note that the lifetime selected for the result is
+ // equal to the smaller of the lifetimes of the
+ // parameters
+
+ if x.len() > y.len() {
+ x
+ }
+ else {
+ y
+ }
+}
+
+struct ImportantExcerpt<'a> {
+ part: &'a str,
+}
+
+fn main() {
+ let string1 = String::from("abcd");
+ {
+ let string2 = "xyz";
+
+ let result = longest(string1.as_str(), string2);
+ //dbg!(result);
+ }
+
+ let script = String::from("Before time began, there was the cube. We know not where it comes from.");
+ let first_sentence = script.split('.')
+ .next()
+ .expect("Could not find a '.'");
+ let i = ImportantExcerpt { part: first_sentence };
+ dbg!(i.part);
+}