如何从方法返回特征的实例? [英] How do I return an instance of a trait from a method?

查看:22
本文介绍了如何从方法返回特征的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个返回 Shader 特性实例的函数.这是我大幅简化的代码:

I'm trying to create a function that returns an instance of the Shader trait. Here is my drastically simplified code:

trait Shader {}

struct MyShader;
impl Shader for MyShader {}

struct GraphicsContext;

impl GraphicsContext {
    fn create_shader(&self) -> Shader {
        let shader = MyShader;
        shader
    }
}

fn main() {}

但是我收到以下错误:

error[E0277]: the trait bound `Shader + 'static: std::marker::Sized` is not satisfied
  --> src/main.rs:10:32
   |
10 |     fn create_shader(&self) -> Shader {
   |                                ^^^^^^ `Shader + 'static` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `Shader + 'static`
   = note: the return type of a function must have a statically known size

较新版本的编译器有此错误:

Newer versions of the compiler have this error:

error[E0277]: the size for values of type `(dyn Shader + 'static)` cannot be known at compilation time
 --> src/main.rs:9:32
  |
9 |     fn create_shader(&self) -> Shader {
  |                                ^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn Shader + 'static)`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: the return type of a function must have a statically known size

这是有道理的,因为编译器不知道 trait 的大小,但我找不到推荐的修复方法.据我所知,使用 & 传回引用是行不通的,因为引用会超过其创建者的生命周期.

This makes sense as the compiler doesn't know the size of the trait, but nowhere can I find the recommended way of fixing this. Passing back a reference with & wouldn't work as far as I know because the reference would outlive the lifetime of its creator.

也许我需要使用Box?

推荐答案

Rust 1.26 及更高版本

impl Trait 现在存在:

fn create_shader(&self) -> impl Shader {
    let shader = MyShader;
    shader
}

它确实有局限性,比如不能在 trait 方法中使用,也不能在具体返回类型是有条件的情况下使用.在这些情况下,您需要使用下面的 trait 对象答案.

It does have limitations, such as not being able to be used in a trait method and it cannot be used when the concrete return type is conditional. In those cases, you need to use the trait object answer below.

您需要返回某种类型的 trait 对象,例如 &TBox,并且您是&T 在这种情况下是不可能的:

You need to return a trait object of some kind, such as &T or Box<T>, and you're right that &T is impossible in this instance:

fn create_shader(&self) -> Box<Shader> {
    let shader = MyShader;
    Box::new(shader)
}

另见:

这篇关于如何从方法返回特征的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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