简体   繁体   English

这个特定的 Rust 代码是如何实现的?

[英]How is this particular Rust code implemented?

I'm reading the documentation for the Amethyst game engine , and I've encountered this interesting piece of code:我正在阅读Amethyst 游戏引擎的文档,并且遇到了这段有趣的代码:

use amethyst::ecs::World;

struct MyResource {
    pub game_score: i32,
}

fn main() {
    let mut world = World::empty();
    
    let my = MyResource {
        game_score: 0,
    };
    
    world.insert(my);
}

And:和:

  // try_fetch returns a Option<Fetch<MyResource>>
  let fetched = world.try_fetch::<MyResource>();
  if let Some(fetched_resource) = fetched {
      //dereference Fetch<MyResource> to access data
      assert_eq!(*fetched_resource, MyResource{ game_score: 0, });
  } else {
      println!("No MyResource present in `World`");
  }

And I don't see how it can work, really.我不明白它是如何工作的,真的。

Apparently, there is some kind of collection inside World that can hold members of a completely arbitrary data type -- how can that be possible?显然,World 内部有某种集合可以保存完全任意数据类型的成员——这怎么可能? The MyResource struct doesn't implement any particular trait, so we can't say something like Box<dyn Trait>. MyResource 结构没有实现任何特定的特征,所以我们不能说像 Box<dyn Trait> 这样的东西。

And then we can recover that item based on its type.然后我们可以根据其类型恢复该项目。 Again, I can't see how this can work.同样,我看不出这是如何工作的。 How can we iterate through a collection and check every item's type?我们如何遍历一个集合并检查每个项目的类型? Is there even a dynamic type checker in Rust? Rust 中是否还有动态类型检查器? Again, the struct does not implement any particular trait, so how can it possibly interface with it at all?同样,该结构没有实现任何特定的特征,那么它怎么可能与它交互呢?

The signature of insert : 插入的签名:

pub fn insert<R>(&mut self, r: R) where
    R: Resource, 

There is a blanket implementation for Resource资源有一个全面的实现

impl<T> Resource for T where
    T: Any + Send + Sync,

There is also a blanket implementation for Any ( Any trait implementors ): Any ( Any trait implementors ) 也有一个全面的实现:

impl<T> Any for T where
    T: 'static + ?Sized, 

The Any docs are probably also relevant. Any 文档可能也相关。

Conclusion : your MyResource does implement a relevant trait, namely the Resource trait.结论:您的 MyResource 确实实现了相关特征,即 Resource 特征。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM