< 返回版块

forex24 发表于 2023-08-12 13:04

有个自定义类型,内部包含了一个Vec字段,我不想暴露这个字段,想在自定义类型实现切片操作

pub struct MyClass { series: Vec<...> }

希望能这样

let slice = &MyClass[0..];

评论区

写评论
jellybobbin 2023-08-13 16:25

nice

--
👇
aj3n: ```rust use std::ops::Index;

struct Foo { bar: Vec, }

impl Index for Foo where [Foo]: Index, { type Output = <[Foo] as Index>::Output;

fn index(&self, idx: Idx) -> &Self::Output {
    &self.bar.as_slice()[idx]
}

}


像这样?
aj3n 2023-08-13 00:30
use std::ops::Index;

struct Foo {
    bar: Vec<Self>,
}

impl<Idx> Index<Idx> for Foo
where
    [Foo]: Index<Idx>,
{
    type Output = <[Foo] as Index<Idx>>::Output;

    fn index(&self, idx: Idx) -> &Self::Output {
        &self.bar.as_slice()[idx]
    }
}

像这样?

作者 forex24 2023-08-12 20:08

终于实现了,就是代码太丑了,有没有更好的办法


impl Index<Range<usize>> for CandleSeries {
    type Output = [Candle];

    fn index(&self, index: Range<usize>) -> &Self::Output {
        &self.candles[index.start..index.end]
    }
}

impl Index<RangeFull> for CandleSeries {
    type Output = [Candle];

    fn index(&self, _index: RangeFull) -> &Self::Output {
       self.candles.as_slice()
    }
}

impl Index<RangeFrom<usize>> for CandleSeries {
    type Output = [Candle];

    fn index(&self, index: RangeFrom<usize>) -> &Self::Output {
        &self.candles[index.start..]
    }
}

impl Index<RangeTo<usize>> for CandleSeries {
    type Output = [Candle];

    fn index(&self, index: RangeTo<usize>) -> &Self::Output {
        &self.candles[..index.end]
    }
}

impl Index<RangeToInclusive<usize>> for CandleSeries {
    type Output = [Candle];

    fn index(&self, index: RangeToInclusive<usize>) -> &Self::Output {
        &self.candles[..=index.end]
    }
}

impl Index<RangeInclusive<usize>> for CandleSeries {
    type Output = [Candle];

    fn index(&self, index: RangeInclusive<usize>) -> &Self::Output {
        &self.candles[*index.start()..=*index.end()]
    }
}
yuyidegit 2023-08-12 15:48

可以试试这个

pub struct MyClass {
    series: Vec<i32>,
}

impl std::ops::Deref for MyClass {
    type Target = [i32];

    fn deref(&self) -> &Self::Target {
        &self.series
    }
}
LongRiver 2023-08-12 13:46

实现 Index trait?https://doc.rust-lang.org/std/ops/trait.Index.html

就像 Vec 那样。https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-Index%3CI%3E-for-Vec%3CT,+A%3E

1 共 5 条评论, 1 页