Reputation: 41
I want to perform a very simple task, but I cannot manage to stop the compiler from complaining.
fn transform(s: String) -> String {
let bytes = s.as_bytes();
format!("{}/{}", bytes[0..2], bytes[2..4])
}
[u8]
does not have a constant size known at compile-time.
Some tips making this operation to work as intended?
Upvotes: 3
Views: 212
Reputation: 16630
Indeed, the size of a [u8]
isn't known at compile time. The size of &[u8]
however is known at compile time because it's just a pointer plus a usize
representing the length of sequence.
format!("{:?}/{:?}", &bytes[0..2], &bytes[2..4])
Rust strings are encoded in utf-8, so working with strings in this way is generally a bad idea because a single unicode character may consist of multiple bytes.
Upvotes: 5