Rust String implements both AsRef<str> and AsRef<[u8]>
But why does Rust correctly allow String to be borrowed as &str but not as &[u8] even when we provide explicit type annotation hint?
let s = String::from("hello");
let item: &str = &s; // Works
let item2: &[u8] = &s; // Fails
Ofcourse explicit invocation works, but curious why above doesn't work
let item2: &[u8] = s.as_ref();
When a &String coerces to &str, that happens via the Deref trait (not AsRef, and not Borrow). The Deref trait is not generic — it only allows one type to be chosen to “dereference to”. In the case of String, that's str.
The AsRef and Borrow traits are not special to the compiler. They are available for generic code to use explicitly, not implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With