Created
April 11, 2019 06:41
-
-
Save rust-play/6b352b0c9896688cddbbdea9e672207a to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![allow(unused_variables)] | |
| #![allow(dead_code)] | |
| use std::fmt::{Display, Formatter, Result}; | |
| struct ImportantExcerpt<'a> { | |
| part: &'a str, | |
| } | |
| impl<'b> std::fmt::Display for ImportantExcerpt<'b> { | |
| fn fmt(&self, f: &mut Formatter) -> Result { | |
| write!( | |
| f, | |
| "(excerpt include this part: {})", | |
| self.announce_and_return_part("hey") | |
| ) | |
| } | |
| } | |
| impl<'a> ImportantExcerpt<'a> { | |
| fn announce_and_return_part(&self, announcement: &str) -> &str { | |
| println!("Attention please: {}", announcement); | |
| self.part | |
| } | |
| fn what_a_life(&self, x: &'a str, y: &'a str, show: impl Display) -> &'a str { | |
| if x.len() > y.len() { | |
| self.announce_and_return_part(&format!("{}", show)); | |
| x | |
| } else { | |
| y | |
| } | |
| } | |
| } | |
| 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 novel = String::from("Call me Ishmael. Some years ago..."); | |
| let novel = String::from("Call me Ishmael"); | |
| let first_sentence = novel.split('.').next().expect("Could not find a '.'"); | |
| let i = ImportantExcerpt { | |
| part: first_sentence, | |
| }; | |
| println!("struct is {}", i); | |
| { | |
| let string1 = String::from("long string is long"); | |
| let string2 = String::from("xyz"); | |
| let result = longest_with_an_announcement(string1.as_str(), string2.as_str(), "haha"); | |
| println!("The longest string is {}", result); | |
| println!("{}", i.what_a_life(string1.as_str(), string2.as_str(), 333)) | |
| } | |
| } | |
| fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { | |
| if x.len() > y.len() { | |
| x | |
| } else { | |
| y | |
| } | |
| } | |
| fn no_clue(x: &str, y: &str) -> String { | |
| String::from("really long string"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment