rust - 我如何在这里返回&str?

标签 rust

当我尝试运行此命令时:

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/

相关文章:

rust - 生成器似乎没有公开 `resume()` 方法

rust - 将可变引用移出可变对象

rust - 将宏参数传递给其他宏

rust - 为什么对已删除对象的可变引用仍算作可变引用?

rust - Rust wasm 中的 Closure::new 和 Closure::wrap 有什么区别

rust - 如何在 3 中安装 Rust crate?

rust - 为实现 Trait 的类型实现 Borrow<Trait>

rust FFI。转换为 void 指针

arrays - 使用 #[!no_std] 通过 FFI 将数组从 C 传递到 Rust

random - 如何用种子确定性地洗牌数组?