3

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

damn thx. Comming from high level languages doenst make me smart i guess.
feel free to mention anything you would like to have clarified :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.