-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.rs
More file actions
45 lines (38 loc) · 1.7 KB
/
Copy pathstart.rs
File metadata and controls
45 lines (38 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// This file demonstrates a Rust function that uses generics, lifetimes, and trait bounds.
// Import the `Display` trait from the `std::fmt` module.
// The `Display` trait allows for user-facing formatting, like printing to the console.
use std::fmt::Display;
// Define a function that finds the longest of two string slices and prints an announcement.
// `<'a, T>`: Declares generics. 'a is a lifetime, and T is a type.
fn longest_with_an_announcement<'a, T>(
x: &'a str, // `x` is a reference to a string slice with lifetime 'a.
y: &'a str, // `y` is another string slice, also with lifetime 'a.
ann: T, // `ann` is a parameter of the generic type T.
) -> &'a str // The function returns a string slice that lives as long as 'a.
where
// `T: Display` is a "trait bound". It requires that the generic type T
// must be a type that implements the `Display` trait.
T: Display,
{
// Print the announcement. The `{}` formatting works because `ann`'s type `T`
// is guaranteed to implement the `Display` trait.
println!("Announcement! {}", ann);
// Compare the lengths of the two string slices.
if x.len() > y.len() {
// If `x` is longer, return it.
x
} else {
// Otherwise, return `y`.
y
}
}
// The main function, which is the entry point of the program.
fn main() {
let string1 = String::from("a long string is long");
let string2 = "xyz";
// Define an announcement. A string literal `&'static str` implements Display.
let announcement = "Today's winner is...";
// Call the function.
let result = longest_with_an_announcement(string1.as_str(), string2, announcement);
println!("The longest string is: {}", result);
}