Home
Rust
String to_lowercase Example
Updated Apr 18, 2025
Dot Net Perls
To_lowercase. In Rust we can transform strings from lowercase to uppercase, and the opposite, with built-in functions. It is also possible to transform strings in-place, avoiding an allocation.
For ASCII strings, we have more options. The "make" functions only are available for ASCII, as transforming the case of ASCII data never changes its length.
This Rust program acts on str references. We call the ASCII lowercase and uppercase functions first, and print the results with println.
Tip The "to" functions copy the string data and return a string. This means we can call them on str references, as no modifications occur.
fn main() { let value = "BIRD"; // Lowercase and uppercase the string. let result = value.to_ascii_lowercase(); println!("{}", result); let result = value.to_ascii_uppercase(); println!("{}", result); // This has the same result. let result = value.to_lowercase(); println!("{}", result); let result = value.to_uppercase(); println!("{}", result); }
bird BIRD bird BIRD
Make lowercase. For the "make" methods, we can only act on ASCII data. A String is needed, and we cannot call make_ascii_lowercase() on a str reference.
Info With make_ascii_lowercase, the original data is modified in-place, so we must have a String.
Here We call to_string() on the str literal to create a String, so that it can be modified in-place.
Tip We must make the variable we call these functions on mutable, so we use the "mut" keyword.
fn main() { let mut value = "SNOW".to_string(); // Modify the string in-place. value.make_ascii_lowercase(); println!("{}", value); value.make_ascii_uppercase(); println!("{}", value); }
snow SNOW
For performance, modifying existing data (as with make_ascii_lowercase) is faster, but a String is needed. So the opportunity for optimization is fairly narrow here.
The standard library in Rust is powerful, well-designed and fairly extensive. It allows us to lowercase and uppercase strings in many ways, and provides some optimizations.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 18, 2025 (image).
Home
Changes
© 2007-2025 Sam Allen