How to pass mixed items to a vec which implements trait without dyn

Hello,
A simplified version of the code is as below. If I use this code as is, its compiling.

use core::ops::*;

#[derive(Debug)]
pub enum IndexSliceOp {
    Index(i64),
    Range(Range<i64>),
}

pub trait IntoIndexSliceOp {
    fn into_slice_op(self) -> IndexSliceOp;
}

impl IntoIndexSliceOp for i64 {
    fn into_slice_op(self) -> IndexSliceOp {
        IndexSliceOp::Index(self)
    }
}

impl IntoIndexSliceOp for Range<i64> {
    fn into_slice_op(self) -> IndexSliceOp {
        IndexSliceOp::Range(self)
    }
}

But when I try to pass mixed parameters to the function via a vec like below, its not working

fn main() {
    do_something(vec![10, 10..20])
}

I know that that I can solve it by rewriting the code as below, but I feel its not that ergonomic as the one I am trying to achieve. Any other suggestions to achieve the same ?

pub fn do_something(slices: Vec<IndexSliceOp>) {
    todo!()
}

fn main() {
    do_something(vec![10i64.into_slice_op(), (10i64..20).into_slice_op()])
}

It is fundamentally impossible to have mixed types directly in a Vec, because Vec relies on uniform size of elements and doesn't have any place to put additional info about each element. You have to use dyn or an enum.

1 Like

Thanks for the info

You can write you own macro.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.