Skip to content

Instantly share code, notes, and snippets.

@wolflee
Forked from rust-play/playground.rs
Created April 11, 2019 06:43
Show Gist options
  • Save wolflee/2d6c1bdc40fd89849b58720feffa13c7 to your computer and use it in GitHub Desktop.
Save wolflee/2d6c1bdc40fd89849b58720feffa13c7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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