Use the to_uppercase() and to_lowercase() methods on string slices (&str) or String types to convert text, which return a new String containing the transformed characters. These methods handle Unicode case mapping correctly, unlike simple ASCII-only loops, but remember that the original string remains unchanged because Rust strings are immutable by default.
Here is a practical example showing how to convert both owned String values and string slices:
fn main() {
let original = String::from("Rust Programming");
// Convert to uppercase (returns a new String)
let upper = original.to_uppercase();
// Convert to lowercase (returns a new String)
let lower = original.to_lowercase();
// Works directly on string slices too
let slice = "HELLO WORLD";
let slice_lower = slice.to_lowercase();
println!("Original: {}", original);
println!("Upper: {}", upper);
println!("Lower: {}", lower);
println!("Slice Lower: {}", slice_lower);
}
If you need to modify a String in place to save memory, you can overwrite the variable with the result of the conversion. For example, my_string = my_string.to_uppercase(); replaces the old value with the new one. Note that to_uppercase() and to_lowercase() are not constant-time operations; they iterate through the string and perform Unicode case folding, which can be slightly slower than simple ASCII shifts but is necessary for correct internationalization support.
For performance-critical scenarios where you know the input is strictly ASCII, you can use the ascii crate or standard library methods like to_ascii_uppercase() on individual characters, but for general application logic, the standard to_uppercase() and to_lowercase() methods are the idiomatic and safest choice. They automatically handle edge cases like the German "ß" (which becomes "SS" in uppercase) or Turkish dotted/dotless "i" variations depending on the Unicode data version.