Str::as_bytes (again)

This is something where Rust's lifetimes can help.

The signature is <'a> &'a str -> &'a [u8]. That tells you three things:

  • The input is immutably borrowed (well, you have to know that str doesn't have interior mutability, but that's the normal case, and is essential for string literals, so hopefully it's not a surprise), so whatever it's doing can't change the input string
  • The output is a reference, so it has to be returning a reference to something that already exists (as opposed to if it were -> String or -> Vec<u8>, which is owned and thus could be something new)
  • The output reference has the same lifetime as the input lifetime, so it must be returning a reference to the same stuff that was passed in (well, technically it could also return a static, but you know that as_bytes isn't doing return &[1, 2, 3];)

Thus yes, it's a different view on the same underlying data.

(You can apply this same kind of thinking to understand other things like from_ref in std::array - Rust too.)