< 返回我的博客

berners 发表于 2023-03-13 11:37

Tags:生命周期,租借权

我在看教程的时候看到生命周期,然后回看前面的教程: When I read the tutorial, I see the Lifetime chapter, and then look back at the previous chapter .There is one of that sample code:

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

这里的calculate_length引用和usize为什么可以不要求以生命周期'a的形式去声明?而且这里也不会报错。 Why can calculate_length and usize not be declared in the form of lifetime 'a ? And there will be no error here. 我看生命周期的教程时都要写成类似于这样: When I read the lifetime tutorial, I should write something like this:

fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    if s2.len() > s1.len() {
        s2
    } else {
        s1
    }
}

评论区

写评论
meloalright 2023-03-26 17:30

usize 这里是拷贝

Snowmanzzz 2023-03-23 21:16

ellision

1 共 2 条评论, 1 页