Newbie: str.as_bytes -> mem::transmute documentation vs reality

str.as_bytes uses mem::transmute. The mem::transmute documentation says that this copies the bytes.

But I find it hard to believe that as_bytes, which is used everywhere, include str.len, would be so involved. Further, a simple test shows that if you mutate the returned bytes, the original string is mutated.

So, either I'm misunderstanding mem::transmute's documentation, or I'm missing something very obvious.

A &str is represented in the following manner:

struct Str {
    data: *const u8,
    len: usize,
}

A &[u8] is represented in the following manner:

struct ByteSlice {
    data: *const u8,
    len: usize,
}

When as_bytes uses transmute, the bytes that are copied are the 16 bytes that make up that pointer and length. The data behind the pointer is not copied.

5 Likes

Thanks,
That makes some sense re mem::transmute.

But I'm still confused, if str has a len, why not use that directly? Maybe I'm looking at the wrong thing?

The language doesn't have any built-in syntax for accessing the length field of a &str. It's a special type provided by the compiler.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.