我正在尝试创建一个函数,该函数返回实现
然而,我收到了以下错误提示:
这很有道理,因为编译器不知道trait的大小,但我找不到修复此问题的推荐方法。 据我所知,使用
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>
?
impl Trait
实际上创建了一个通用函数,它使用静态多态性。因此,如果目标是具有动态多态性(即在运行时更改行为),仍然最好返回一个(装箱的)特质对象,即Box<dyn Shader>
。 - JoaoBaptimpl Shader
?我处于这样一种情况:我不需要条件返回类型,因为实现trait的每个结构体只会返回特定的变量。但是我仍然被迫使用Box<dyn Shader>
方法,因为我需要使用trait方法。 - Meet Sinojia