rust - 如何从方法返回特征的实例?

标签 rust traits

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

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

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

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 的大小,但我在任何地方都找不到修复此问题的推荐方法。 使用 & 传回引用据我所知是行不通的,因为该引用文献将比其创建者的生命周期更长。

也许我需要使用 Box<T>

最佳答案

Rust 1.26 及更高版本

impl Trait now exists :

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

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

Rust 1.0 及更高版本

您需要返回某种特征对象,例如&TBox<T> ,你是对的 &T在这种情况下是不可能的:

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

另见:

关于rust - 如何从方法返回特征的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30661046/

相关文章:

rust - 在继承自另一个特征的特征中指定关联类型

arrays - 我的3D数组长度为2,但在运行时访问索引2紧急情况

sqlite - 如何存储 SQLite 准备好的语句供以后使用?

rust - 为什么 `std::env::args` 返回 `String` 的迭代器而不是 `&' static str`?

rust - 如何处理 flat_map 中的结果

rust - "overflow evaluating the requirement"尝试延迟关联类型时

rust - 无法实现自定义特征的 io::Read

rust - 为什么我会收到错误 "the trait ` Iterator` is not implemented"以引用泛型类型,即使它实现了 IntoIterator?

scala - Scala 线性化函数的基本原理

scala - 如何模式匹配扩展多个特征的对象?