Search code examples
rustutf-8iteratoruppercase

How to make a Character (char) uppercase in Rust


In the rustlings, in `iterators2.rs', I need to capitalize the first letter of a word.

This is the code that I have

pub fn capitalize_first(input: &str) -> String {
    let mut c = input.chars();
    return match c.next() {
        None => String::new(),
        Some(first) => first.to_uppercase(),
    };
}

The issue I get is

  --> exercises/standard_library_types/iterators2.rs:13:24
   |
11 |       return match c.next() {
   |  ____________-
12 | |         None => String::new(),
   | |                 ------------- this is found to be of type `String`
13 | |         Some(first) => first.to_uppercase(),
   | |                        ^^^^^^^^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
   | |                        |
   | |                        expected struct `String`, found struct `ToUppercase`
14 | |     };
   | |_____- `match` arms have incompatible types

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

Why does char.to_uppercase() return struct ToUppercase and not a capitalized char?


Solution

  • The reason why is that we are in a big world and Rust strings are encoded in UTF-8, allowing for different languages and characters to be encoded correctly. In some languages, a lowercase letter might be one character, but its uppercase form is two characters.

    For this reason, char.to_uppercase() return an iterator that must be collected to get the appropriate result.

    Some(first) => first.to_uppercase().collect() should fix this issue