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.
First example. This 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.
Detail We call to_string() on the str literal to create a String, so that it can be modified in-place.
Detail 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
Performance review. 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.
A summary. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.