fn main() {
let s = String::from("hello dj");
//字符串字面值实际就是字符串的切片,所以
let ss ="hello dj";
//&s[..]其实等价于ss
let s1 = first_word(&s[..]);
println!("s1 is {}",s1);
let s2 = first_word(ss);
println!("s2 is {}",s2);
}
//&str是字符串 slice 类型
fn first_word(s: &str) -> &str {
//as_bytes 方法将 String 转化为字节数组
let bytes = s.as_bytes();
//通过enumerate获取了元素的索引,和值的引用的所以使用&item。
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
//返回整个字符串的切片
&s[..]
}