【问题标题】:Can you express 'valid for lifetime of returned value' in the lifetime system?你能在生命周期系统中表达“返回值的生命周期有效”吗?
【发布时间】:2015-02-17 08:30:30
【问题描述】:

这是我多次遇到的问题。

  • 您有需要执行任务的数据。

  • 您希望安全地将数据发送到任务并远程处理。

  • ...你要等待什么结果。

类似这个围栏的东西:http://is.gd/fnhRta

use std::thread::Thread;

#[derive(Debug)]
struct Foo<'a> {
  fp: &'a u32
}

impl<'a> Foo<'a> {
  fn new(v:&'a u32) -> Foo<'a> {
    return Foo {
      fp: v
    };
  }
}

fn main() {
  let value = 100;
  let foo = Foo::new(&value);
  let guard = Thread::scoped(|| {
    println!("{:?}", foo);
  });

  // We know foo is valid in the remote thread, because guard is in the same 
  // scope of foo... but how do we express that using lifetimes?
  guard.join();
}

是否可以使用生命周期来表达这一点?

本质上只接受 Foo 的东西,其中 是 { ... } 块的生命周期。

【问题讨论】:

  • 此 PR 可能与您要实现的目标有关:github.com/rust-lang/rust/pull/22319
  • 仅供参考,Rust 样式是 4 空格缩进。
  • 请@Shepmaster;我也不使用隐式返回语句;出于同样的原因;我不同意“标准”风格。好不好……我想我们都同意这与问题完全无关。

标签: rust


【解决方案1】:

您编写的代码现在可以工作了:

use std::thread;

#[derive(Debug)]
struct Foo<'a> {
    fp: &'a u32
}

impl<'a> Foo<'a> {
    fn new(v: &'a u32) -> Foo<'a> {
        Foo { fp: v }
    }
}

fn main() {
    let value = 100;
    let foo = Foo::new(&value);
    let guard = thread::scoped(|| {
        println!("{:?}", foo);
    });

    // We know foo is valid in the remote thread, because guard is in the same 
    // scope of foo... but how do we express that using lifetimes?
    guard.join();
}

这可能是由于RFC 458 放宽了对Send / Sync 的限制。现在,thread::scoped 返回一个与闭包具有相同生命周期的JoinGuard

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2013-04-06
    相关资源
    最近更新 更多