Reputation: 1319
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.
Upvotes: 2
Views: 822
Reputation: 430634
You cannot overload the reference operator, but you can hook into Deref
coercion:
impl std::ops::Deref for Buffer {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.data
}
}
Your original code works in this case.
See also:
Upvotes: 4
Reputation: 732
You are calling the whole struct with print_slice(&buffer);
but only the data
field with print_slice(buffer.as_ref())
. If you make it print_slice(&buffer.data)
it will work. Alternatively change the type signature of the print_slice
function to expect &Buffer
, which will make the as_ref()
line not work.
Upvotes: 1