在‘iterators2.rs’中,我需要大写单词的第一个字母。
这是我拥有的代码
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
return match c.next() {
None => String::new(),
Some(first) => first.to_uppercase(),
};
}
我得到的问题是
--> 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`.
为什么char.to_uppercase()返回结构ToUppercase
而不是大写字符?
发布于 2021-11-14 01:07:51
原因是我们处在一个很大的世界里,Rust字符串是用UTF-8编码的,允许不同的语言和字符被正确编码。在某些语言中,小写字母可能是一个字符,但其大写形式是两个字符。
因此,char.to_uppercase()
返回一个迭代器,必须收集该迭代器才能获得适当的结果。
Some(first) => first.to_uppercase().collect()
应该可以解决这个问题
https://stackoverflow.com/questions/69959520
复制相似问题