繁体   English   中英

特质不能成为一个对象

[英]trait cannot be made into an object

我正在研究光线跟踪器,并希望模拟所有的hitable对象以提供通用接口。

我实现了一个名为Object的特性,所有的hitable对象都实现了。 我创建了一个名为Intersection的结构,它包含一个f32值和一个实现Object trait的struct的引用。

编码:

use std::sync::atomic::{AtomicUsize, Ordering};
use super::ray::Ray;
use std::ops::{Index};

static mut ID : AtomicUsize = AtomicUsize::new(0);

pub trait Object {
    fn intersection<'a, T: Object>(&self, ray: &Ray) -> Intersections<'a, T>;
    fn get_uid() -> usize {
        unsafe {
            ID.fetch_add(1, Ordering::SeqCst);
            ID.load(Ordering::SeqCst)
        }
    }
}

pub struct Intersection<'a, T: Object>{
    pub t: f32,
    pub obj: &'a T,
}

impl<'a, T: Object> Intersection<'a, T> {
    pub fn new(t: f32, obj: &'a Object) -> Intersection<'a, T> {
        Self {t, obj}
    }
}

pub struct Intersections<'a, T: Object> {
    pub hits: Vec<Intersection<'a, T>>,
}

impl<'a, T: Object> Intersections<'a, T> {
    pub fn new() -> Self {
        Self {
            hits: Vec::new(),
        }
    }
    pub fn push(&self, hit: Intersection<'a, T>) {
        self.hits.push(hit);
    }
    pub fn len(&self) -> usize {
        self.hits.len()
    }
}

错误消息如下:

error[E0038]: the trait `object::Object` cannot be made into an object
  --> src/object.rs:23:5
   |
23 |     pub fn new(t: f32, obj: &'a Object) -> Intersection<'a, T> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `object::Object` cannot be made into an object
   |
   = note: method `intersection` has generic type parameters
   = note: method `get_uid` has no receiver

由于我在交集中存储引用,我认为它不必处理结构的实际大小。

我很确定Intersection不应该是通用的,而应该包含一个&Object

pub struct Intersection<'a>{
    pub t: f32,
    pub obj: &'a Object,
}

如果你真的需要Intersection的实际对象类型,那么Object::intersection应该不是通用的,但是应该返回一个Intersection<Self>

pub trait Object<'a> {
    fn intersection(&self, ray: &Ray) -> Intersections<'a, Self>;
}

错误的第二部分涉及get_uid 如果要通过引用访问特征,它不能成为特征的一部分,因为在这种情况下只能使用带有self参数的函数。

另请注意, get_uid并不符合您的想法:如果两个线程同时调用它,则两者都有可能得到相同的结果。 你想要的是:

fn get_object_uid() -> usize { // <- Renamed because it needs to be outside the trait
    unsafe {
        ID.fetch_add (1, Ordering::SeqCst) + 1
    }
}

暂无
暂无

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

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