#Destructure array and share common vector elements

15 messages · Page 1 of 1 (latest)

clear compass
#

I essentially have a situation like this:

let x = vec![
  500,
  600,
  700,
  1,
  2,
  3,
];
let y = vec![
  4,
  5,
  500,
  600,
  700,
  6,
  7,
];

And I want to pull the 500, 600, 700, out of the two vecs.

I tried using a macro:

macro_rules! common {
  () => {
    500,
    600,
    700,
  }

let x = vec![
  common!(),
  1,
  2,
  3,
];
let y = vec![
  4,
  5,
  common!(),
  6,
  7,
];

which doesn't work.

And I tried destructuring an array:

const fn common() -> [usize; 3] {
  [500, 600, 700]
}

let x = vec![
  ..common(),
  1,
  2,
  3,
];
let y = vec![
  4,
  5,
  ..common(),
  6,
  7,
];

Which also doesn't work.

What's the right way to do this?

#

Is it possible to do this while staying inline? (I.e. not writing code before or after the vec![] to, say, extend a mut Vec<usize> or something like that)

quaint grove
#

doesnt look like vec! supports any kind of syntax like that

#

you can pretty easily go to definition rs macro_rules! vec { () => ( $crate::__rust_force_expr!($crate::vec::Vec::new()) ); ($elem:expr; $n:expr) => ( $crate::__rust_force_expr!($crate::vec::from_elem($elem, $n)) ); ($($x:expr),+ $(,)?) => ( $crate::__rust_force_expr!(<[_]>::into_vec(box [$($x),+])) ); }

clear compass
#

So what would be a solid way to handle this? Write an extended version of the vec! macro that supports this?

quaint grove
#

you probably could write a macro like that

clear compass
#

There has to be an easier way though, right? This is something that works natively in other languages like JS.

const arr1 = [1, 2, 3];
const combined = [...arr1, 4, 5];
#

I feel like there should be either an RFC for this or a macro. I can't be the first one running into this?

#

Destructure array and share common vector elements

quaint grove
#

simplest ways I can think of, unless theres a crate for it, is to either use chained iterators and .collect::<Vec<_>>(), or use .extend( on existing Vecs

quaint grove
#

@clear compass like this

#

?eval ```rs
let vec1 = vec![1, 2, 3];
let vec2 = [vec1.as_slice(), &[4, 5, 6]]
.into_iter()
.flatten()
.copied()
.collect::<Vec<_>>();
vec2

frail jasperBOT
#
     Running `target/debug/playground`

[1, 2, 3, 4, 5, 6]
quaint grove
#

you might want to try an approach that doesnt involve combining the collections into one first though

#

to avoid unnecessary cloning everywhere