rust - 为什么 Rust 中的泛型[有时]不需要生命周期说明符?

标签 rust lifetime

我正在查看 Microsoft Rust 指南,在阅读泛型章节时,我遇到了以下问题。

考虑以下两段代码:

struct Point<T>
{
    x: T,
    y: T,
}
fn main()
{
    let intro = Point{ x: "Hello", y: "World" };    
}
struct Point
{
    x: &str,
    y: &str,
}
fn main()
{
    let intro = Point{ x: "Hello", y: "World" };    
}

x 和 y 的类型均为 &str。 为什么编译器能够推断第一部分的生命周期,而不能推断第二部分的生命周期?

最佳答案

第一种情况:

struct Point<T>
{
    x: T,
    y: T,
}
fn main()
{
    let intro = Point{ x: "Hello", y: "World" };    
}

类型定义对于任何 T 都有效,尤其是对于引用具有的任何生命周期(如果存在引用)。它是一个泛型,旨在适应(并在必要时产生几个不同的“真实”结构)。

您使用的具体结构是 T&'static str 但它可能是另一个生命周期。

第二种情况

struct Point
{
    x: &str,
    y: &str,
}
fn main()
{
    let intro = Point{ x: "Hello", y: "World" };    
}

没有通用的。所以它一定是一个完全定义的类型。这意味着如果有引用,就必须有一生。您没有指定生命周期,因此这是一个错误。

如果您只想在一生中自由决定,那么它又是通用的:

struct Point<'a> {
    x: &'a str,
    y: &'a str,
}
fn main()
{
    let intro = Point{ x: "Hello", y: "World" };    
}

或者,如果您希望 Point 仅对静态引用有效,您可以将其定义为

struct Point {
    x: &'static str,
    y: &'static str,
}

关于rust - 为什么 Rust 中的泛型[有时]不需要生命周期说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67970377/

相关文章:

url - Rust URL 删除特定的 GET 参数

rust - 如何更新结构,将大部分但不是所有字段设置为默认值?

macros - 错误 : variable 'x' is still repeating at this depth

javascript - 在 javascript 方法中定义的数组的生命周期

rust - 如何为 `IntoIter` 绑定(bind) `<&Self as IntoIterator>` 类型?

rust - 为什么不安全的代码可以编译,但推送到向量的类似代码会提示引用的生命周期不够长?

rust - 当输出值不属于类型时如何实现 std::ops::Index

rust - 什么是非词汇生命周期?

rust - 通用关联类型的生命周期可能不够长

rust - 如何获得关联实体的变换?