Why is capitalizing the first letter of a string so convoluted in Rust?

問題:

I'd like to capitalize the first letter of a &str .我想將&str的第一個字母大寫。 It's a simple problem and I hope for a simple solution.這是一個簡單的問題,我希望有一個簡單的解決方案。 Intuition tells me to do something like this:直覺告訴我做這樣的事情:

let mut s = "foobar";
s[0] = s[0].to_uppercase();

But &str s can't be indexed like this.但是&str不能像這樣被索引。 The only way I've been able to do it seems overly convoluted.我能夠做到的唯一方法似乎過於複雜。 I convert the &str to an iterator, convert the iterator to a vector, upper case the first item in the vector, which creates an iterator, which I index into, creating an Option , which I unwrap to give me the upper-cased first letter.我將&str轉換爲迭代器,將迭代器轉換爲向量,將向量中的第一項大寫,這將創建一個迭代器,我對其進行索引,創建一個Option ,我將其解開以提供大寫的第一個字母. Then I convert the vector into an iterator, which I convert into a String , which I convert to a &str .然後我將向量轉換爲迭代器,將其轉換爲String ,然後將其轉換爲&str

let s1 = "foobar";
let mut v: Vec<char> = s1.chars().collect();
v[0] = v[0].to_uppercase().nth(0).unwrap();
let s2: String = v.into_iter().collect();
let s3 = &s2;

Is there an easier way than this, and if so, what?有沒有比這更簡單的方法,如果有,那又怎樣? If not, why is Rust designed this way?如果不是,爲什麼 Rust 是這樣設計的?

Similar question 類似問題


解決方案:

參考: https://stackoom.com/en/question/2b9MP
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章