Ownership และ Borrowing
Rust Slices: &str and &[T]
Borrow part of a string or array without copying a single byte.
สิ่งที่คุณจะได้เรียนรู้
- String slices
- Array slices
- Returning a slice
&numbers[1..4]
100
201
302
403
504
A view of part of a collection
A slice is a reference to a continuous part of a collection. &text[0..5] borrows the first five bytes of a string, and &numbers[1..4] borrows three items of an array.
first_word returns a slice of the text it was given, so nothing is copied. find returns the position of the first space, or None when there is none. A slice of an array works the same way and has methods such as iter and len.
ประเด็นสำคัญ
- &
text[0..5]borrows the first five bytes. - A slice does not copy the data.
- &
numbers[1..4]has three items.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(index) => &text[..index],
None => text,
}
}
fn main() {
let sentence = String::from("ownership makes Rust safe");
println!("{}", first_word(&sentence));
println!("{}", &sentence[10..15]);
let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4];
println!("{:?} sum = {}", middle, middle.iter().sum::<i32>());
}
ownership
makes
[20, 30, 40] sum = 90ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- คำที่ยาวที่สุด หาคำที่ยาวที่สุดในประโยค ง่าย
- Every Other Character Keep the characters at even positions. ง่าย