Skip to content

Instantly share code, notes, and snippets.

@eignnx
Last active March 7, 2020 00:43
Show Gist options
  • Select an option

  • Save eignnx/113fabd8ede9e732e9110e2b586f5832 to your computer and use it in GitHub Desktop.

Select an option

Save eignnx/113fabd8ede9e732e9110e2b586f5832 to your computer and use it in GitHub Desktop.
why
fn slice_of_slice<'pool, 'slice, 'ret>(
pool: &'pool [usize],
slice: &'slice [usize],
) -> &'ret [usize]
where
'pool: 'slice, // `pool` outlives `slice`
'slice: 'ret, // `slice` outlives the return value
{
// Most of this is bullshit so that both `slice` and `pool` are used.
let pool_idx = slice[0];
let slice_idx = pool[pool_idx];
&slice[slice_idx..slice_idx + 1]
}
#[test]
fn test_slice_of_slice() {
let pool = vec![1, 2, 3, 1, 2, 99, 3, 1, 1, 1, 2, 3, 4, 2];
let ret = {
let slice = &pool[3..6]; // == &[1, 99, 2]
slice_of_slice(&pool, slice)
}; // `slice` is dropped here.
// `ret` is still alive.
assert_eq!(ret, &[99]); // I thought `slice` had to outlive `ret`!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment