File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed
Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -9,7 +9,8 @@ fn main() {
99 basics:: basics ( ) ;
1010 println ! ( ) ;
1111 stuff:: collections ( ) ;
12- stuff:: error_handling ( ) ;
12+ stuff:: lifetimes ( ) ;
1313 println ! ( ) ;
14+ stuff:: error_handling ( ) ;
1415 guessgame:: guess_game ( ) ;
1516}
Original file line number Diff line number Diff line change 11use core:: panic;
22use std:: {
3+ fmt:: Display ,
34 fs:: File ,
45 io:: { ErrorKind , Read } ,
56} ;
@@ -32,3 +33,26 @@ fn read_username_from_file() -> Result<String, std::io::Error> {
3233 File :: open ( "hello.txt" ) ?. read_to_string ( & mut s) ?;
3334 Ok ( s)
3435}
36+
37+ pub fn lifetimes ( ) {
38+ let string1 = String :: from ( "long string is long" ) ;
39+ {
40+ let string2 = String :: from ( "xyz" ) ;
41+ let result = longest ( string1. as_str ( ) , string2. as_str ( ) ) ;
42+ println ! ( "lifetimes: the longest string is {}" , result) ;
43+
44+ longest_with_announcement ( string1. as_str ( ) , string2. as_str ( ) , "hoho!" ) ;
45+ }
46+ }
47+
48+ fn longest < ' a > ( x : & ' a str , y : & ' a str ) -> & ' a str {
49+ if x. len ( ) > y. len ( ) { x } else { y }
50+ }
51+
52+ fn longest_with_announcement < ' a , T > ( x : & ' a str , y : & ' a str , ann : T ) -> & ' a str
53+ where
54+ T : Display ,
55+ {
56+ println ! ( "Announcement! {}" , ann) ;
57+ if x. len ( ) > y. len ( ) { x } else { y }
58+ }
You can’t perform that action at this time.
0 commit comments