I've implemented AsRef<[u8]>
for my type and the automatic conversion to &[u8]
using .as_ref()
works but the &
-operator doesn't... how can I make the operator work?
struct Buffer {
data: Vec<u8>,
}
impl AsRef<[u8]> for Buffer {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
fn print_slice(slice: &[u8]) {
slice.iter().for_each(|b| print!("{:02x}", b));
println!()
}
fn main() {
let buffer = Buffer {
data: b"Testolope".to_vec(),
};
// print_slice(&buffer); // <- This does not work
print_slice(buffer.as_ref()) // <- This works
}
error[E0308]: mismatched types
--> src/main.rs:20:17
|
20 | print_slice(&buffer);
| ^^^^^^^ expected slice, found struct `Buffer`
|
= note: expected type `&[u8]`
found type `&Buffer`
I want a generic solution. Other datatypes like Vec<u8>
support the conversion to &[u8]
by using the &
-operator. It would be cool if I could make this work for my own types so that I don't have to use .as_ref()
every time.