我正在查看 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/