Determination of service life for comparison with consumed cost
I have a code that is simplified looks like this:
enum A<'a> {
AConst(&'a [u8])
}
trait FromA {
fn from_a(A) -> Self;
}
impl FromA for &[u8] {
fn from_a(a: A) -> &[u8] {
match a {
AConst(bytes) => bytes
}
}
}
fn main() {
// I'd like to use it like this:
let s = b"abc";
let a = AConst(s);
let foo: &[u8] = from_a(a);
}
This doesn't work as the compiler complains about missing lifetime specifiers on &[u8]
. Now I'm not sure what the right life will be. Since it from_a
consumes its own argument, the lifetime of the returned reference clearly cannot be the same as the lifetime of the argument.
Is there a way to use annotations for life to achieve this? If so, what would be the correct annotations? Can we somehow introduce a type A
to carry the lifetime information of the link?
source to share
Can we somehow introduce a type
A
to carry the lifetime information of the link?
This is actually what you do when you write
enum A<'a> { //'
AConst(&'a [u8]) //'
}
The full type here A<'a>
means that it A
contains a reference to the lifetime 'a
.
To be correct, you need to explicitly propagate this lifetime in the definition and implementation of your definition:
trait FromA<'a> { //'
fn from_a(A<'a>) -> Self; //'
}
impl<'a> FromA<'a> for &'a [u8] { //'
fn from_a(a: A<'a>) -> &'a [u8] {
match a {
AConst(bytes) => bytes
}
}
}
Thus: The lifetime of a segment &[u8]
is the lifetime of the link contained in the object A
.
Then you can:
fn main() {
let s = b"abc";
let a = AConst(s);
let foo: &[u8] = FromA::from_a(a);
println!("{}", foo);
}
[97, 98, 99]
source to share