fn sub(foo: &String) {
    println!("We got this string: [{}]", foo);
}

fn main() {
    // "Hello", 0x00, 0x00, "!"
    let buf: [u8; 8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x00, 0x00, 0x21];

    // Create a string from the byte array above, interpret as UTF-8, ignore decoding errors.
    let lossy_unicode = String::from_utf8_lossy(&buf).to_string();

    sub(&lossy_unicode);
}

Create a string from a byte array, but the result isn’t a string, it’s a cow 🐮, so you need another to_string() to convert your ā€œstringā€ into a string.

I still have a lot to learn.

(into_owned() instead of to_string() also works and makes more sense to me, it’s just that the compiler suggested to_string() first, which led to this funny example.)

⤋ Read More

Participate

Login or Register to join in on this yarn.