Avoiding unnecessary init

Given this:

struct Builder {
  id: [u8; 32],
}

impl Builder {
  fn new(id: &[u8; 32]) -> Self {
    let idc = id.something(); // ???
    Self {
      id: idc,
    }
  }
}

Is there a way to initialize Builder::id/idc immediately from the input id, without first having to initialize an array (let idc = [0u8; 32];)? MaybeUninit::write_slice() looks promising, but it's nightly only.

  fn new(id: &[u8; 32]) -> Self {
    let id = id.clone();
    Self {
      id
    }
  }
1 Like

Or just:

  fn new(id: &[u8; 32]) -> Self {
    let id = *id;
    Self {
      id
    }
  }
6 Likes

Or just:

fn new(&id: &[u8; 32]) -> Self {
    Self {
        id
    }
}
4 Likes

What manner of black magic is this? :thinking:

That is to say, I had no idea one could do that!

It's called the pattern.

In case you missed it, this is the key change:

fn new(&id: &[u8; 32]) -> Self {
//     ^

And here's a relevant blog post on the topic.

2 Likes

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.