【发布时间】:2016-11-15 12:25:13
【问题描述】:
我正在尝试为 String 实现一个新特征,该特征具有将每个 String 的第一个字母大写并取消大写其余部分的函数。我将函数的接口基于 Rust 标准库中的 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,但这些迭代器类型无法收集以形成字符串。有什么建议吗?
【问题讨论】:
标签: rust