summaryrefslogtreecommitdiff
path: root/rust-book/lifetimes
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
commit67cdcc2e12118becb823e20a40cc2687f2b8425a (patch)
treeed92c3234b89079e6d4cf36f5e80c5ffa79def48 /rust-book/lifetimes
parente25482fca375d318a39c3b54db396b0db6e0b263 (diff)
downloadlearning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz
learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip
Started Rust in Action MEAP.
Diffstat (limited to 'rust-book/lifetimes')
-rwxr-xr-xrust-book/lifetimes/Cargo.lock4
-rwxr-xr-xrust-book/lifetimes/Cargo.toml7
-rwxr-xr-xrust-book/lifetimes/src/main.rs43
3 files changed, 54 insertions, 0 deletions
diff --git a/rust-book/lifetimes/Cargo.lock b/rust-book/lifetimes/Cargo.lock
new file mode 100755
index 0000000..0c2507e
--- /dev/null
+++ b/rust-book/lifetimes/Cargo.lock
@@ -0,0 +1,4 @@
+[[package]]
+name = "lifetimes"
+version = "0.1.0"
+
diff --git a/rust-book/lifetimes/Cargo.toml b/rust-book/lifetimes/Cargo.toml
new file mode 100755
index 0000000..8003864
--- /dev/null
+++ b/rust-book/lifetimes/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "lifetimes"
+version = "0.1.0"
+authors = ["53hornet <53hornet@gmail.com>"]
+edition = "2018"
+
+[dependencies]
diff --git a/rust-book/lifetimes/src/main.rs b/rust-book/lifetimes/src/main.rs
new file mode 100755
index 0000000..87b6ce6
--- /dev/null
+++ b/rust-book/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);
+}