簡體   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