简体   繁体   English

实现 Size 特征

[英]Implementing Sized trait

Created a simple struct that implements Sized trait.创建了一个实现 Sized 特征的简单结构。

struct FixedIndividual<T: Sized,A: cmp::Ord, >{
    chromosome: T,
    score: Option<A>,
}
impl<T: Sized, A: cmp::Ord> FixedIndividual<T,A>{
    fn new(chromosome: T) -> Self{
        FixedIndividual { chromosome , score: None}
    }
}

However, I've managed to create an instance that includes Vec(implement only?Size),但是,我设法创建了一个包含 Vec(仅实现?大小)的实例,

 #[test]
    fn init_vector(){
        let chromosome: Vec<i32> = vec![1,2,3,4,5];
        let chromosome_cpy = chromosome.clone();
        let indv:FixedIndividual<Vec<i32>, OrderedFloat<f64>> = FixedIndividual::new(chromosome);
        assert_eq!(indv.score, None);
        assert_eq!( indv.chromosome
                    .iter()
                    .zip(chromosome_cpy.iter())
                    .all(|(a,b)| a == b ), true);
    } 

Created a simple struct that implements Sized trait.创建了一个实现 Sized 特征的简单结构。

Your bounds are useless, generic bounds are Sized by default, you have to opt out of it.您的界限是无用的,默认情况下通用界限是Sized的,您必须选择退出它。

However, I've managed to create an instance that includes Vec(implement only?Size),但是,我设法创建了一个包含 Vec(仅实现?大小)的实例,

Not sure where you got that idea, and ?Sized is not a trait, it's only a bound which means the type (or function) is sizedness-agnostic .不知道你从哪里得到这个想法,并且?Sized不是一个特征,它只是一个界限,这意味着类型(或函数)是sizeness-agnostic That doesn't imply it's unsized itself.这并不意味着它本身没有大小。 For instance Box<T> has T: ?Sized , meaning T may be sized or unsized.例如Box<T>T: ?Sized ,这意味着T可以调整大小或不调整大小。 Box is sized either way.无论哪种方式, Box的大小都是如此。

A type being unsized means it implements !Sized , which rather few types do.未调整大小的类型意味着它实现了!Sized ,而很少有类型这样做。

That's fine because Vec s are Sized , like almost all struct values.这很好,因为VecSized ,就像几乎所有struct值一样。 The actual Vec value does not contain its elements, but instead references them, so it has a defined, constant size no matter how many elements there are, similar to how a pointer is stored in an integer value.实际的Vec值不包含其元素,而是引用它们,因此无论有多少元素,它都具有定义的恒定大小,类似于指针如何存储在 integer 值中。 You may also have confused vecs with slices, such as [i32] , which are ?Sized .您可能还会将 vecs 与切片混淆,例如[i32] ,它们是?Sized

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

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