study_rust_example/generic_traits_lifetime/
mix_usage.rs1use core::fmt;
2use std::fmt::Debug;
3use std::fmt::Display;
4
5pub fn longer_str_with_announcement<'a, T>(str1: &'a str, str2: &'a str, anno: T) -> &'a str
6where
7 T: Display + Debug,
8{
9 println!("Announcement: {}", anno);
10 if str1.len() >= str2.len() {
11 str1
12 } else {
13 str2
14 }
15}
16
17#[derive(Debug)]
18struct Announcement<'a> {
19 anno: &'a str,
20 time: &'a str,
21}
22
23impl<'a> Announcement<'a> {}
24
25impl<'a> fmt::Display for Announcement<'a> {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 write!(f, "Debug anno: {}, time: {}", self.anno, self.time)
28 }
29}
30
31pub fn mix_usage_study() {
32 let anno1 = "display in longer_str_with_announcement.";
33 let str1 = "longer test str1";
34 let str2 = String::from("longer test str2.");
35 let str_longer = longer_str_with_announcement(&str1, &str2, &anno1);
36 println!("str longer {}", str_longer);
37 let time = String::from("2023年 9月11日 星期一 12时16分36秒 CST");
38 let anno2 = Announcement {
39 anno: &anno1,
40 time: &time,
41 };
42 let str_longer2 = longer_str_with_announcement(&str1, &str2, &anno2);
43 println!("str longer2 {}", str_longer2);
44}