Newb,here.Copied this from Rust Book.Fiddling with it.Is there better way to do this?From watching live coding streams,a lot of the time this kind of thing gets written much 'shorter' instead of what i did here.Input would be much appreciated.
pub fn run() {
1 println!("This is the life_times.rs file.");
2 let string1 = String::from("abcd");
3 let string2 = "xyz";
4
5 let result = longest_with_an_announcement(
6 string1.as_str(),
7 string2,
8 "Today is someone's birthday!",
9 );
10 println!("The longest string is {}", result);
11
12 let result = shortest_with_an_announcement(
13 string1.as_str(),
14 string2,
15 "I hope this works.",
16 );
17 println!("The shortest string is {}", result);
18 }
19
20 use std::fmt::Display;
21
22 fn longest_with_an_announcement<'a, T>(
23 x: &'a str,
24 y: &'a str,
25 ann: T,
26 ) -> &'a str
27 where
28 T: Display,
29 {
30 println!("Announcement! {}", ann);
31 if x.len() > y.len() {
32 x
33 } else {
34 y
35 }
36 }
37
38 fn shortest_with_an_announcement<'b, T>(
39 x: &'b str,
40 y: &'b str,
41 ann: T,
42 ) -> &'b str
43 where
44 T: Display,
45 {
46 println!("Announcement! {}", ann);
47 if x.len() < y.len() {
48 x
} else {
y
}