rust - Figuring out lifetime for reference from a consumed value -



rust - Figuring out lifetime for reference from a consumed value -

i have code that, simplified, looks this:

enum a<'a> { aconst(&'a [u8]) } trait froma { fn from_a(a) -> self; } impl froma &[u8] { fn from_a(a: a) -> &[u8] { match { aconst(bytes) => bytes } } } fn main() { // i'd utilize this: allow s = b"abc"; allow = aconst(s); allow foo: &[u8] = from_a(a); }

this doesn't work, compiler complains missing lifetime specifiers on &[u8]. i'm not sure right lifetime be. from_a consumes argument, lifetime of returned reference cannot same lifetime of argument.

is possible somehow utilize lifetime annotations accomplish this? if is, right annotations be? can somehow create a type carry info lifetime of reference?

can somehow create a type carry info lifetime of reference?

that in fact doing when writing

enum a<'a> { //' aconst(&'a [u8]) //' }

the total type here a<'a> meaning a carries within reference of lifetime 'a.

to correct, need propagate explicitly lifetime in trait definition , implementation :

trait froma<'a> { //' fn from_a(a<'a>) -> self; //' } impl<'a> froma<'a> &'a [u8] { //' fn from_a(a: a<'a>) -> &'a [u8] { match { aconst(bytes) => bytes } } }

thus saying : lifetime of &[u8] piece lifetime of reference contained in a object.

you can :

fn main() { allow s = b"abc"; allow = aconst(s); allow foo: &[u8] = froma::from_a(a); println!("{}", foo); } [97, 98, 99]

rust lifetime

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -