Reputation: 6500
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();
Upvotes: 4
Views: 443
Reputation: 43842
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.
Upvotes: 6