2

I have a 3-element array:

let color = [0.25, 0.25, 0.25];

I'd like to turn it into a 4-element array, which would be the 3-element array plus one appended element:

let color_with_alpha = [color[0], color[1], color[2], 1.0];

I know Rust has some cool syntax sugar for a lot of things; is there something for this? Something like:

let color_with_alpha = [color, 1.0];

I've read about the concat macro but that seems to only create string slices. I would imagine there's a vector-based solution but I don't require the dynamic sizing.

3
  • Why not just use push? If you need to keep the first vector, just use clone(), bind it to a variable, and then push to that. If you can't use clone, and can't consume color, then the odds are that this syntax sugar wouldn't work even if it was implemented. If dynamic resizing is an issue, let color_with_alpha = Vec::with_capacity(color.len() + 1); Commented Mar 17, 2018 at 5:49
  • @BHustus color is an Array, not a Vector. Commented Mar 17, 2018 at 5:54
  • Wow, I actually forgot that Rust has standard arrays, hah. Sorry. Commented Mar 17, 2018 at 5:55

1 Answer 1

3

No, there is no such syntax.

It's always hard to prove a negative, but I've implemented a parser of Rust code and I've used Rust for over 3 years; I've never encountered any such syntax.


The closest I can imagine would be to implement a trait for array of various sizes. This is complicated because you cannot move out of non-Copy arrays. Since there's no generic integers, you'd have to implement this trait for every size of array you needed.

trait ArrayAppend<T> {
    type Output;
    fn append(self, val: T) -> Self::Output;
}

impl<T: Copy> ArrayAppend<T> for [T; 3] {
    type Output = [T; 4];

    fn append(self, val: T) -> Self::Output {
        [self[0], self[1], self[2], val]
    }
}

fn main() {
    let color = [0.25, 0.25, 0.25];
    let color2 = color.append(1.0);
}
Sign up to request clarification or add additional context in comments.

1 Comment

If I can ask these kinds a different way I'm open to your thoughts, but yeah, I guess that's kind of how these questions go :) Thanks for the insight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.