我试图在特征中找到构造函数的例子,但运气不好.这是Rust的惯用之处吗?
trait A {
fn new() -> A;
}
struct B;
impl A for B {
fn new() -> B {
B
}
}
fn main() {
println!("message")
}
Run Code Online (Sandbox Code Playgroud)
<anon>:7:8: 9:9 error: method `new` has an incompatible type for trait: expected trait A, found struct `B` [E0053]
<anon>:7 fn new() -> B {
<anon>:8 B
<anon>:9 }
<anon>:7:8: 9:9 help: see the detailed explanation for E0053
error: aborting due to previous error
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)
转换它会返回core …
我是这门语言的新手,还在与借阅检查员打架.我已经看到一些库使用new()函数,也就是没有参数的构造函数,它可以工作.基本上这意味着返回的数据是在新的函数范围内创建的,并且在新范围的末尾不会被删除.
当我自己尝试这个时,借用检查器不会让这个代码通过.除了将i32可变引用作为参数传递给构造函数之外,如何使这个工作.
我错过了什么吗?
#[derive(Debug)]
struct B<'a> {
b: &'a i32
}
#[derive(Debug)]
struct A<'a> {
one: B<'a>
}
impl<'a> A<'a> {
fn new() -> A<'a> {
// let mut b = 10i32;
A {
one: B{b: &mut 10i32}
}
}
}
fn main() {
let a = A::new();
println!("A -> {:?}", a);
}
Run Code Online (Sandbox Code Playgroud)
编译器错误.
main.rs:15:19: 15:24 error: borrowed value does not live long enough
main.rs:15 one: B{b: &mut 10i32}
^~~~~
main.rs:12:20: 17:3 note: reference must be valid for the lifetime …Run Code Online (Sandbox Code Playgroud) 基本上,通过组合不同的组件来构造对象(struct).每个具体组件都可以被与界面匹配的另一个组件轻松交换(我想特性).
我目前正试图实现让我遇到一些错误的特性,并让我开始思考这是否是Rust中常见的事情.
// usage example
fn main() {
let obj = MainObject::new(Component1::new(), Component2::new(), Component3());
// Where each component is a type(struct) with some well predefined methods.
}
Run Code Online (Sandbox Code Playgroud)
这背后的主要思想是实现游戏中常用的组件模式.基本上游戏将包含许多不同的对象,行为和包含的数据略有不同.对象由标准组件组成,而不是具有大类层次结构,更完整的示例.
pub struct Container
{
input: InputHandlerComponent, // Probably a trait
physics: PhysicsComponent, // Probably a trait
renderer: RendererCompoent // Probably a trait
}
impl Container {
fn new(p: PhysicsComponent, i: InputComponent, r: RenderComponent) -> Container {
Container {input: i, physics: p, renderer: r}
}
}
struct ConcretePhysicsComponent;
impl PhysicsComponent for ConcretePhysicsComponent
{ …Run Code Online (Sandbox Code Playgroud)