The code below compiles and runs but if I change Client::new()
as indicated in the comment then I get an error (E0759) regarding the 'static
lifetime.
-
Shouldn't
Client::new()
reject the argument as it does not live for the entire duration of the program? -
The field in
Client
is of typeConn<'static>
so why does the code compile when usingc.to_vec().into()
ifc
does not live as long as'static
? -
Why does it not compile when using
c.clone()
ifConn
'sclone
implementation also callsto_vec()
?
Thanks in advance!
#[derive(Debug)]
enum Conn<'a> {
Vec(Vec<u8>),
Ref(&'a [u8]),
}
impl<'a> AsRef<[u8]> for Conn<'a> {
fn as_ref(&self) -> &[u8] {
match self {
Conn::Vec(v) => v.as_ref(),
Conn::Ref(r) => r,
}
}
}
impl<'a> From<Vec<u8>> for Conn<'a> {
fn from(v: Vec<u8>) -> Self {
Self::Vec(v)
}
}
impl<'a> Clone for Conn<'a> {
#[inline]
fn clone(&self) -> Self {
Self::from(self.as_ref().to_vec())
}
}
impl<'a> std::ops::Deref for Conn<'a> {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
match self {
Conn::Vec(v) => v.as_ref(),
Conn::Ref(v) => v,
}
}
}
#[derive(Debug)]
struct Client {
c: Conn<'static>
}
impl Client {
fn new(c: &Conn) -> Self {
Self { c: c.to_vec().into() }
}
}
// this produces error E0759
// impl Client {
// fn new(c: &Conn) -> Self {
// Self { c: c.clone() }
// }
// }
fn main() {
let c = Conn::Vec(Vec::new());
let client = Client::new(&c);
println!("client: {:?}", client);
}