本文介绍了为什么`Arc<Mutex<dyn MyTrait>>`会自动获得静态生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的例子中,renderer 的类型是 std::sync::Arc>.这是我现在代码中的一个问题,我不知道为什么会发生这种情况.

In this simple example, renderer is having the type std::sync::Arc<std::sync::Mutex<(dyn Renderer + 'static)>>. This is a problem for me on my code right now, and I don't know why it happens.

use std::sync::Arc;
use std::sync::Mutex;

pub type OnConsume = Arc<dyn Fn() -> Option<u32> + Send + Sync>;

pub trait Renderer {
    fn set_on_consume(&mut self, f: OnConsume);
}
pub struct Stream {
    pub renderer: Arc<Mutex<dyn Renderer>>,
}

fn main() {}

为什么Arc> 有静态生命周期?

Why Arc<Mutex<dyn MyTrait>> has static lifetime?

推荐答案

我们知道结构体 Stream 没有附加任何生命周期,因此它可以存活多长时间没有限制.

We know that the struct Stream does not have any lifetimes attached to it, so there are no restrictions on how long it can live.

在最坏的情况下,Stream 可能有 'static 的生命周期,并且由于它的所有字段都必须持续那么长时间,dyn Renderer> 必须始终假设这种最坏的情况是正确的.

In the worst case scenario, Stream could have a lifetime of 'static and since all of its fields must last that long, dyn Renderer must always assume this worst case scenario to be true.

然而,我们可以为 Stream 添加一个明确的生命周期,以表明它的生命周期仅限于 dyn Renderer 的生命周期.这样,编译器就知道它们必须具有相同的生命周期,并且会将其正确匹配到您的用例.

We can however add an explicit lifetime to Stream to indicate that its lifetime is restricted to that of dyn Renderer. This way the compiler knows they must have the same lifetime and will correctly match it to your use case.

pub struct Stream<'a> {
    pub renderer: Arc<Mutex<dyn Renderer + 'a>>,
}

这篇关于为什么`Arc&lt;Mutex&lt;dyn MyTrait&gt;&gt;`会自动获得静态生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:17