This commit is contained in:
TimLai666 2024-06-10 16:59:52 +08:00 committed by GitHub
parent 1b767ffd5b
commit 28d4095cdd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 16 additions and 26 deletions

View File

@ -1,17 +1,11 @@
# Vectors
# 向量
Vectors are one of the most-used Rust data structures. In other programming
languages, they'd simply be called Arrays, but since Rust operates on a
bit of a lower level, an array in Rust is stored on the stack (meaning it
can't grow or shrink, and the size needs to be known at compile time),
and a Vector is stored in the heap (where these restrictions do not apply).
向量是 Rust 中使用最廣泛的資料結構之一。在其他程式語言中,它們可能被簡單地稱為數組,但由於 Rust 操作的是較低層次的數據,數組在 Rust 中是存儲在棧上的stack意味著它不能增長或縮小大小需要在編譯時知道而向量是存儲在堆上的heap這些限制不適用
Vectors are a bit of a later chapter in the book, but we think that they're
useful enough to talk about them a bit earlier. We shall be talking about
the other useful data structure, hash maps, later.
向量在書中屬於稍後的章節,但我們認為它們足夠有用,值得提前介紹。我們將在後面討論另一個有用的資料結構:雜湊表。
## Further information
## 更多資訊
- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html)
- [使用向量存儲值列表](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html)
- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut)
- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map)

View File

@ -1,17 +1,16 @@
// vecs1.rs
//
// Your task is to create a `Vec` which holds the exact same elements as in the
// array `a`.
// 您的任務是創建一個 `Vec`,其中包含與陣列 `a` 完全相同的元素。
//
// Make me compile and pass the test!
// 讓我編譯並通過測試!
//
// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint.
// 執行 `rustlings hint vecs1` 或使用 `hint` watch 子命令來獲取提示。
// I AM NOT DONE
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = // TODO: declare your vector here with the macro for vectors
let a = [10, 20, 30, 40]; // 一個普通的陣列
let v = // TODO: 使用向量的巨集在這裡宣告您的向量
(a, v)
}

View File

@ -1,29 +1,26 @@
// vecs2.rs
//
// A Vec of even numbers is given. Your task is to complete the loop so that
// each number in the Vec is multiplied by 2.
// 給定了一個包含偶數的 Vec。您的任務是完成循環使 Vec 中的每個數字都乘以 2。
//
// Make me pass the test!
// 讓我通過測試!
//
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.
// 執行 `rustlings hint vecs2` 或使用 `hint` watch 子命令來獲取提示。
// I AM NOT DONE
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for element in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
// TODO: 填寫這裡,使 Vec `v` 中的每個元素都乘以 2。
???
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
// 在這個點,`v` 應該等於 [4, 8, 12, 16, 20]。
v
}
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|element| {
// TODO: Do the same thing as above - but instead of mutating the
// Vec, you can just return the new number!
// TODO: 做與上面相同的事情 - 但不修改 Vec您可以直接返回新的數字
???
}).collect()
}