- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 167字
- 2021-07-02 13:35:17
Vectors
Vectors are like arrays, except that their content or length doesn't need to be known in advance and can grow on demand. They are allocated on the heap. They can be created by either calling the Vec::new constructor or by using the vec![] macro:
// vec.rs
fn main() {
let mut numbers_vec: Vec<u8> = Vec::new();
numbers_vec.push(1);
numbers_vec.push(2);
let mut vec_with_macro = vec![1];
vec_with_macro.push(2);
let _ = vec_with_macro.pop(); // value ignored with `_`
let message = if numbers_vec == vec_with_macro {
"They are equal"
} else {
"Nah! They look different to me"
};
println!("{} {:?} {:?}", message, numbers_vec, vec_with_macro);
}
In the preceding code, we created two vectors, numbers_vec and vec_with_macro, in different ways. We can push elements to our vector using push() method and can remove elements using pop(). There are more methods for you to explore if you go to their documentation page: https://doc.rust-lang.org/std/vec/struct.Vec.html . Vectors can also be iterated using the for loop syntax as they also implement the Iterator trait.
推薦閱讀
- The Complete Rust Programming Reference Guide
- Android開發(fā)精要
- Apache Spark 2 for Beginners
- Android 7編程入門經(jīng)典:使用Android Studio 2(第4版)
- Wireshark Network Security
- Object-Oriented JavaScript(Second Edition)
- 精通Python自動化編程
- PLC應用技術(三菱FX2N系列)
- Mastering openFrameworks:Creative Coding Demystified
- Node.js開發(fā)指南
- Canvas Cookbook
- SEO教程:搜索引擎優(yōu)化入門與進階(第3版)
- Java設計模式深入研究
- 算法超簡單:趣味游戲帶你輕松入門與實踐
- ASP.NET 4權威指南