私は、各文字列の最初の文字を大文字にし、残りを大文字にする関数を持つ文字列の新しい特性を実装しようとしています。私は錆の標準ライブラリのto_uppercase()
とto_lowercase()
に関数のインターフェイスを基にしています。複数のイテレータ・タイプからどのように収集しますか?
use std::io;
trait ToCapitalized {
fn to_capitalized(&self) -> String;
}
impl ToCapitalized for String {
fn to_capitalized(&self) -> String {
self.chars().enumerate().map(|(i, c)| {
match i {
0 => c.to_uppercase(),
_ => c.to_lowercase(),
}
}).collect()
}
}
fn main() {
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).ok().expect("Unable to read from stdin.");
println!("{}", buffer.to_capitalized());
}
このコードは、here所定の提案に基づいて、しかしコードが古くなって、複数のコンパイルエラーが発生しています。
src/main.rs:10:13: 13:14 error: match arms have incompatible types [E0308]
src/main.rs:10 match i {
^
src/main.rs:10:13: 13:14 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:10:13: 13:14 note: expected type `std::char::ToUppercase`
src/main.rs:10:13: 13:14 note: found type `std::char::ToLowercase`
src/main.rs:12:22: 12:38 note: match arm with an incompatible type
src/main.rs:12 _ => c.to_lowercase(),
だから要するに、fn to_uppercase(&self) -> ToUppercase
とfn to_lowercase(&self) -> ToLowercase
の戻り値は、マップは現在、複数の戻り値の型を持っているので、一緒に収集することができません:私は今、私の実装を持っています唯一の問題は、次のエラーです。
Bytes
とChars
のような共通のイテレータタイプにキャストしようとしましたが、これらのイテレータタイプを収集して文字列を形成することはできません。助言がありますか?ここで
[簡略化してやや最適化できます](https://play.rust-lang.org/?gist=dfa85b1d5e07d8e5e29785c5e530ee76) – Shepmaster