下面的代码不会编译,因为编译器认为我不应该分配给 t1
因为它是借用的,但实际上函数 always_returns_no_lifetime
将始终返回实际上没有生命周期的枚举变体,所以我可以修改 t1
。我怎样才能让编译器理解这个或者我应该如何重新组织我的代码来避免这个错误发生?
#[derive(Clone)]
enum Types<'a> {
NoLifetime(i32),
AlsoNoLifetime(i32),
AlsoAlsoNoLifetime(i32),
HasLifetime(&'a str)
}
fn always_returns_no_lifetime<'a>(some_type: &'a Types) -> Types<'a> {
match *some_type {
Types::HasLifetime(text) => panic!("I only return the type that has no lifetime"),
_ => some_type.clone()
}
}
fn main() {
let mut t1 = Types::NoLifetime(20);
let copy = always_returns_no_lifetime(&t1);
t1 = Types::NoLifetime(30);
}
错误是:
error[E0506]: cannot assign to `t1` because it is borrowed
--> src/main.rs:23:5
|
21 | let copy = always_returns_no_lifetime(&t1);
| -- borrow of `t1` occurs here
22 |
23 | t1 = Types::NoLifetime(30);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `t1` occurs here
最佳答案
函数的返回类型错误。如果保证返回值没有任何生命周期,那么它应该被标记为这样,而不是绑定(bind)到任意生命周期:
fn always_returns_no_lifetime(...) -> Types<'static>;
通过此更改,您实际上也不再需要任何输入 生命周期,因为它们仅用于绑定(bind)输入和输出,导致以下签名:
fn always_returns_no_lifetime(some_type: &Types) -> Types<'static>;
不幸的是,这意味着 clone
现在不在表中,因为它克隆了生命周期,所以实现也必须改变:
fn always_returns_no_lifetime(some_type: &Types) -> Types<'static> {
match *some_type {
Types::HasLifetime(_)
=> panic!("I only return values that have no lifetime"),
Types::NoLifetime(i) => Types::NoLifetime(i),
Types::AlsoNoLifetime(i) => Types::AlsoNoLifetime(i),
Types::AlsoAlsoNoLifetime(i) => Types::AlsoAlsoNoLifetime(i),
}
}
此实现的好处可以在以下示例中展示:
fn tie<'a>(text: &'a str) -> Types<'a> {
if text[0] == 'a' {
Types::HasLifetime(text)
} else {
Types::NoLifetime(0)
}
}
fn main() {
let no_lifetime = {
let string = String::from("Hello, world");
let has_lifetime = tie(&*string);
always_returns_no_lifetime(&has_lifetime)
};
// Requires deriving Debug, all structs really should...
println!("{:?}", no_lifetime);
}
如果在不需要时保留生命周期,则无法编译此示例,这是不必要的限制。
关于enums - 如何告诉编译器我返回的枚举的变体总是没有生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144646/