#Help with traits with generic types and lifetimes

5 messages · Page 1 of 1 (latest)

charred flume
#

Hello, so I've got a trait like so

trait FieldRW<T> {
  fn read<'a>(&self, buf: &'a [u8; 512]) -> &'a T;
}

The idea here is that FieldRW is implemented on different types for different handling of serializing and deserializing values to and from a byte array in different ways

I want an implementation for &str such that part of a buffer is parsed as utf8, and returns a &str which lives as long as the byte array buf does

impl FieldRw<&str> for Field {
  fn read<'a>(&self, buf: &'a [u8; 512]) -> &'a str {
    std::str::from_utf8(&buf[self.offset..self.offset+self.length]).unwrap()
  }
}

the range of the array isn't particularly relevant to the question, however because my T is &str and the return type for read is &'a T, Rust expects me to return &'a &str which doesn't feel right. I've thought of letting T be str but that's unsized so it doesn't seem right either. How can I tell the compiler that I simply want to return &'a str?

gloomy granite
#

why not implement FieldRw<str> instead of FieldRw<&str>?

#

if T is str, then &'a T is &'a str

limpid valve
#

just make T: ?Sized

charred flume
#

Huh, that seems to have worked though I'm not sure what it does. What is this called so I can read more about it? It seems similar to trait bounds which I am familiar with