“dyn"是什么意思?是指类型? [英] What does "dyn" mean in a type?

查看:180
本文介绍了“dyn"是什么意思?是指类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近看到使用 dyn 关键字的代码:

I have recently seen code using the dyn keyword:

fn foo(arg: &dyn Display) {}

fn bar() -> Box<dyn Display> {}

这个语法是什么意思?

推荐答案

TL;DR:这是一种用于指定 trait 对象 类型的语法,为了清晰起见必须指定.

TL;DR: It's a syntax for specifying the type of a trait object and must be specified for clarity reasons.

自 Rust 1.0 以来,traits 过着双重生活.一旦声明了特征,它就可以用作特征或类型:

Since Rust 1.0, traits have led a double life. Once a trait has been declared, it can be used either as a trait or as a type:

// As a trait
impl MyTrait for SomeType {}

// As a type!
impl MyTrait {}
impl AnotherTrait for MyTrait {}

正如您想象的那样,这种双重含义可能会引起一些混乱.此外,由于 MyTrait 类型是未调整大小/动态调整大小的类型,这会使人们看到非常复杂的错误消息.

As you can imagine, this double meaning can cause some confusion. Additionally, since the MyTrait type is an unsized / dynamically-sized type, this can expose people to very complex error messages.

为了改善这个问题,RFC2113 引入了 dyn 语法.此语法从 Rust 1.27 开始可用:

To ameliorate this problem, RFC 2113 introduced the dyn syntax. This syntax is available starting in Rust 1.27:

use std::{fmt::Display, sync::Arc};

fn main() {
    let display_ref: &dyn Display = &42;
    let display_box: Box<dyn Display> = Box::new(42);
    let display_arc: Arc<dyn Display> = Arc::new(42);
}

这个新关键字与 impl Trait 语法类似,并努力使类型成为 trait 对象更明显地区别于bare";特征语法.

This new keyword parallels the impl Trait syntax and strives to make the type of a trait object more obviously distinct from the "bare" trait syntax.

dyn 是动态"的缩写.并指 trait 对象执行动态调度这一事实.这意味着确切调用哪个函数的决定将在程序运行时发生.将此与 static dispatch 对比,后者使用 impl Trait 语法.

dyn is short for "dynamic" and refers to the fact that trait objects perform dynamic dispatch. This means that the decision of exactly which function is called will occur at program run time. Contrast this to static dispatch which uses the impl Trait syntax.

没有 dyn 的语法现在已被弃用,很可能在随后的 Rust 版本 它将被删除.

The syntax without dyn is now deprecated and it's likely that in a subsequent edition of Rust it will be removed.

这篇关于“dyn"是什么意思?是指类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆