我正在尝试创建一个返回 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 及更高版本
fn create_shader(&self) -> impl Shader {
let shader = MyShader;
shader
}
它确实有局限性,例如不能在特征方法中使用,并且不能在具体返回类型是有条件的情况下使用。在这些情况下,您需要使用下面的特征对象答案。
Rust 1.0 及更高版本
您需要返回某种特征对象,例如&T
或 Box<T>
,你是对的 &T
在这种情况下是不可能的:
fn create_shader(&self) -> Box<Shader> {
let shader = MyShader;
Box::new(shader)
}
另见:
关于rust - 如何从方法返回特征的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30661046/