79819879

Date: 2025-11-14 10:02:19
Score: 1
Natty:
Report link

Disclaimer: this answer uses satire. Don't read it if you don't like satire.


Here's how, without the pedantry, where s is your string and i is your index:

(s.as_bytes()[i] as char) // Rust deems this safe! Is it, really? Good question.

Naturally, this only works as intended for ASCII strings, since you may already know that UTF-8 is backwards-compatible with ASCII. How do you know if you're dealing with ASCII? Use your brain1.

If you're curious, here's what it looks like to get this wrong. Spoiler:

Nobody dies.

fn print_string(s: &str) {
    for i in 0..s.len() {
        print!("{}", s.as_bytes()[i] as char);
    }

    // Alternatively...
    //  for c in s.as_bytes() {
    //      print!("{}", *c as char);
    //  }

    println!();
}

fn main() {
    print_string("🐶"); // Uh oh.
}

Playground


1 Otherwise, please consult the Am I a Computer Program or a Laterally Thinking Being? handbook that was provided when you took the programmer's oath.

Reasons:
  • Blacklisted phrase (1): How do you
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: invertedPanda