当我尝试运行此命令时:
use std::thread::LocalKey;
struct Person {
name: String,
}
impl Person {
fn new(name: String) -> Self {
Person {
name: name,
}
}
fn name(&self) -> &str {
self.name.as_str()
}
}
thread_local! {
static NAMED_THING: Person = Person::new("John".to_string());
}
fn retrieve_name(p: &'static LocalKey<Person>) -> &str {
p.with(|n| n.name())
}
fn main() {
println!("The name is {}", retrieve_name(&NAMED_THING));
}
它告诉我error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:24:18
|
24 | p.with(|n| n.name())
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 24:12...
--> src/main.rs:24:12
|
24 | p.with(|n| n.name())
| ^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:24:16
|
24 | p.with(|n| n.name())
| ^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that reference does not outlive borrowed content
我可以改为:fn retrieve_name(p: &'static LocalKey<Person>) -> &str {
p.with(|n| n.name().to_owned().as_str())
}
但是每次都克隆该字符串似乎很浪费。更不用说,它现在告诉我:error[E0515]: cannot return value referencing temporary value
--> src/main.rs:24:16
|
24 | p.with(|n| n.name().to_owned().as_str())
| -------------------^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
Playground
最佳答案
你不能做这个。
当线程结束时,Person
将被销毁,然后对其的任何引用(例如,与此同时已发送到另一个线程的'static
引用)将变得悬而未决。这就是LocalKey
具有with
方法的原因,而不是像Deref
变量那样实现lazy_static
的原因:因为将'static
引用引用到线程局部值是不合理的。
您需要组织代码,以便所有借用都限于传递给with
的闭包范围。例如:
fn print_name(p: &'static LocalKey<Person>) {
p.with(|n| println!("The name is {}", n.name()));
}
fn main() {
print_name(&NAMED_THING);
}
关于rust - 我如何在这里返回&str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64083616/