Rust की मूल बातें
Rust Vectors: Vec<T>
A list that grows while the program runs: push, pop, sort and read items safely.
आप क्या सीखेंगे
- vec! and push
- Indexing vs get
- sort and pop
vec![3, 1, 4] after two pushes
30
11
42
1push
5push
A growable list
A vector, written Vec<T>, is a list that can grow and shrink while the program runs. It is the collection you will use most often in Rust.
vec! creates a vector with starting values and push adds to the end. numbers[2] stops the program if the index does not exist, while get returns None instead. pop removes the last item and returns it inside Some.
मुख्य बातें
- push adds to the end, pop removes from the end.
numbers[10]stops the program if the index is missing.get(10)returns None instead.
चलने योग्य Rust उदाहरण
Rust
main.rs
fn main() {
let mut numbers = vec![3, 1, 4];
numbers.push(1);
numbers.push(5);
println!("{:?}", numbers);
println!("length: {}", numbers.len());
println!("third: {}", numbers[2]);
match numbers.get(10) {
Some(value) => println!("found {value}"),
None => println!("no item at index 10"),
}
numbers.sort();
let last = numbers.pop();
println!("{:?} after pop, removed {:?}", numbers, last);
}
[3, 1, 4, 1, 5]
length: 5
third: 4
no item at index 10
[1, 1, 3, 4] after pop, removed Some(5)अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- एक ऐरे का योग सूची में सभी मानों को जोड़ें। आसान
- ऐरे का औसत संख्याओं की सूची का औसत ज्ञात करें। आसान