Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust String AsRef<T> does not auto borrow for [u8]

Tags:

rust

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();
like image 865
Rohit Sharma Avatar asked Oct 21 '25 08:10

Rohit Sharma


1 Answers

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.

like image 159
Kevin Reid Avatar answered Oct 23 '25 23:10

Kevin Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!