You can reverse a string in Rust by converting it to a vector of characters, reversing that vector, and collecting it back into a String, which correctly handles multi-byte Unicode characters. For simple ASCII-only strings, you can also reverse the raw bytes directly for slightly better performance, but the character-based approach is the safest default.
Here is the standard, idiomatic way to handle any valid Unicode string:
fn main() {
let original = "Hello, δΈη!";
let reversed: String = original.chars().rev().collect();
println!("Original: {}", original);
println!("Reversed: {}", reversed);
}
This works because chars() iterates over Unicode scalar values, ensuring that characters like "δΈ" or "η" are treated as single units rather than being split across their underlying UTF-8 bytes. The rev() adapter reverses the iterator, and collect() rebuilds the String.
If you are certain your input contains only ASCII characters (bytes 0β127), you can reverse the byte slice directly to avoid the overhead of character decoding:
fn main() {
let original = "Hello, World!";
let mut bytes = original.as_bytes().to_vec();
bytes.reverse();
let reversed = String::from_utf8(bytes).unwrap();
println!("Reversed: {}", reversed);
}
This byte-level approach is faster because it skips the UTF-8 decoding step, but it will panic or produce garbage output if the string contains non-ASCII characters. Stick to the chars().rev().collect() pattern unless you have a specific performance requirement and have validated the input data.
If you need to reverse a string in place without allocating a new one, you can convert the string to a mutable vector of characters, reverse it, and then convert it back, though this is less common since strings are often immutable in Rust logic. The allocation cost of the collect() method is generally negligible compared to the safety guarantees it provides for internationalized text.