From f23a4fe4bcb7ae0b47d625f89abb281646ea33a7 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Thu, 3 Sep 2020 15:26:30 +0800 Subject: Care about lifetimes --- lifetimes/.gitignore | 18 ++++++++++++++++++ lifetimes/Cargo.toml | 9 +++++++++ lifetimes/src/main.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 lifetimes/.gitignore create mode 100644 lifetimes/Cargo.toml create mode 100644 lifetimes/src/main.rs (limited to 'lifetimes') diff --git a/lifetimes/.gitignore b/lifetimes/.gitignore new file mode 100644 index 0000000..e629269 --- /dev/null +++ b/lifetimes/.gitignore @@ -0,0 +1,18 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/rust +# Edit at https://www.toptal.com/developers/gitignore?templates=rust + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# End of https://www.toptal.com/developers/gitignore/api/rust + diff --git a/lifetimes/Cargo.toml b/lifetimes/Cargo.toml new file mode 100644 index 0000000..3655444 --- /dev/null +++ b/lifetimes/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "lifetimes" +version = "0.1.0" +authors = ["Jordan Gong "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/lifetimes/src/main.rs b/lifetimes/src/main.rs new file mode 100644 index 0000000..8dec31f --- /dev/null +++ b/lifetimes/src/main.rs @@ -0,0 +1,41 @@ +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +use std::fmt::Display; + +// generic type params, trait bound, and lifetimes +fn longest_with_an_announcement<'a, T>( + x: &'a str, + y: &'a str, + ann: T, +) -> &'a str +where + T: Display, +{ + println!("Announcement! {}", ann); + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); + + let result = longest_with_an_announcement( + string1.as_str(), + string2, + "Today is someone's birthday!", + ); + println!("The longest string is {}", result); +} -- cgit v1.2.3