Rust 程式設計影片教程(進階)——004_5 生命週期的例子

linghuyichong發表於2020-01-12

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

結合泛型引數、trait bounds和生命週期

use std::fmt::Display;

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 s1 = String::from("s1");
    let s2 = String::from("s2!");
    let ann = 128;
    let r = longest_with_an_announcement(s1.as_str(), s2.as_str(), ann);
    println!("r = {}", r);
    println!("Hello, world!");
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章