Question

For example:

enum FooBar {
  Bar(Vec<int>),
  Other
}

fn main() {
  let default:&[int] = [];
  let x = Bar(Vec::from_slice([1, 2, 3]));
  let y = match(x) {
    Bar(z) => z.slice(0, z.len()),
    _ => default
  };
  println!("{}", y);
}

In this example the slice is not valid because of the lifetime on z; but we know that the actual data here (x) is valid for the entire block.

Is there some 'a syntax you can use here to help hint this to compiler? If so, how do you do it?

(I believe I've seen some kind of 'a match { } or match x 'a { } / something syntax in the past, but I can't find any examples now that I'm looking)

Was it helpful?

Solution

Sure, there is some syntax, though it is not as explicit on lifetimes as you mean and in fact it is more general. By doing match as you do you are actually moving x into the match, so it is consumed. No wonder that z.slice(...) can't escape the block. But you can avoid moving x into the match by using reference patterns (note the ref before z):

let default: &[int] = [];
let x = Bar(vec![1, 2, 3]);
let y = match x {
    Bar(ref z) => z.slice(0, z.len()),
    Other => default
};
println!("{}", y);

This way x is not moved into match block - its internals are borrowed instead. This program compiles and prints out [1, 2, 3].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top