Char to_lowercase problem

Hi, I tried to convert a char to lowercase, but compile report a type error, any suggestion? Thanks!

use std::collections::BTreeMap;
fn main() {
    let mut new_btm: BTreeMap<char, i32> = BTreeMap::new();
    let c = 'C';
    let l_c = c.to_lowercase().collect();
    new_btm.insert(l_c, 1);
}
error[E0277]: a value of type `char` cannot be built from an iterator over elements of type `char`
 --> src\main.rs:5:32
  |
5 |     let l_c = c.to_lowercase().collect();
  |                                ^^^^^^^ value of type `char` cannot be built from `std::iter::Iterator<Item=char>`
  |
  = help: the trait `FromIterator<char>` is not implemented for `char`

The problem here is that not all Unicode characters can be represented as a single character if you change the case.

For example:

use std::collections::BTreeMap;
fn main() {
    let mut new_btm: BTreeMap<char, i32> = BTreeMap::new();
    let c = 'İ';
    let l_c = c.to_lowercase().collect::<String>();
    println!("len: {}", l_c.len());
    //new_btm.insert(l_c, 1);
}

produces a String of length 3:

len: 3

You can't put that the map if its key is of type char.

If you're only dealing with ASCII characters, you can instead use to_ascii_lowercase():

use std::collections::BTreeMap;
fn main() {
    let mut new_btm: BTreeMap<char, i32> = BTreeMap::new();
    let c = 'C';
    let l_c = c.to_ascii_lowercase();
    new_btm.insert(l_c, 1);
}
1 Like

Thank you!