# Basic 07 : Slice
對擁有序列的資料結構而言, Slice (切片) 是保存部分連續資料的「引用」的好方法。
如我們想要找一個句子裡第一個英文單字...
```Rust=
fn get_first_word(s: &str) -> &str { // 接受字串切片並返回目標切片
let char_arr = s.as_bytes();
for (i, &chr) in char_arr.iter().enumerate() { // 應用 Tuple 解構
match chr {
b'A'..=b'Z' => {}, // A - Z
b'a'..=b'z' => {}, // a - z
_ => return &s[..i]
};
}
&s[..]
}
fn main(){
let mut s = String::from("I am Eroiko!");
let sliced = get_first_word(&s);
/*
* ! clear this object, this operation
* ! will mutate this variable, which
* ! is not allowed since we've use "s"
* ! with immutable reference one line above!
*/
s.clear(); // error
println!("{}", sliced);
}
```
`&str` 是 `String` 物件的「<font size=4 color=mediumSeaGreen>Slice</font>」, 可以參考有序物件的一部分, 好處在於當物件更動後, 參考的結果可以對這些變動做出反應。
由於[可變引用的變數僅允許單一可變引用或全部不可變引用](#basic-06-function), 因此上面 `s.clear()` 那行會導致錯誤, 編譯不通過。
補充一下切片的語法糖。
```Rust=
let s = String::from("Meow");
/* 正常使用 */
&s[1..3]; // "eo", 注意是左閉右開
/* 以下為語法糖 */
&s[..2]; // "Me", 省前
&s[2..]; // "ow", 略後
&s[..]; // "Meow", 都略
&s; // "Meow", 超懶
```