我是铁 rust 新手,我正在用铁 rust 书学习它.
最近,我在那里发现了这个函数:
// Returns the number of characters in the first
// word of the given string
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
如您所见,作者在这里使用了字符串::as_bytes()方法来枚举一个字符串.然后,他们将char‘’转换为U8类型,以判断我们是否已到达第一个单词的末尾.
据我所知,还有另一种 Select ,看起来要好得多:
fn first_word(s: &String) -> usize {
for (i, item) in s.chars().enumerate() {
if item == ' ' {
return i;
}
}
s.len()
}
在这里,我使用的是字符串::chars()方法,该函数看起来要干净得多.
所以问题是:is there any difference between these two things?如果是这样的话,哪一个更好,为什么?