The Rust Programming Language - Understanding Vectors in Rust

The Rust Programming Language - Understanding Vectors in Rust

The Rust Programming Language - Understanding Vectors in Rust. Vectors are re-sizable arrays. Vectors always allocate their data on the heap. A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard library type Vec<T>. The T means that we can have vectors of any type (see the chapter on generics for more).

A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard library type Vec<T>. The T means that we can have vectors of any type (see the chapter on generics for more). Vectors always allocate their data on the heap. You can create them with the vec! macro:


# #![allow(unused_variables)]
#fn main() {
let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
#}

(Notice that unlike the println! macro we’ve used in the past, we use square brackets [] with vec! macro. Rust allows you to use either in either situation, this is just convention.)

There’s an alternate form of vec! for repeating an initial value:


# #![allow(unused_variables)]
#fn main() {
let v = vec![0; 10]; // A vector of ten zeroes.
#}

Vectors store their contents as contiguous arrays of T on the heap. This means that they must be able to know the size of T at compile time (that is, how many bytes are needed to store a T?). The size of some things can't be known at compile time. For these you'll have to store a pointer to that thing: thankfully, the Box type works perfectly for this.

Accessing elements

To get the value at a particular index in the vector, we use []s:


# #![allow(unused_variables)]
#fn main() {
let v = vec![1, 2, 3, 4, 5];

println!("The third element of v is {}", v[2]);
#}

The indices count from 0, so the third element is v[2].

It’s also important to note that you must index with the usize type:

let v = vec![1, 2, 3, 4, 5];

let i: usize = 0;
let j: i32 = 0;

// Works:
v[i];

// Doesn’t:
v[j];

Indexing with a non-usize type gives an error that looks like this:

error: the trait bound `collections::vec::Vec<_> : core::ops::Index<i32>`
is not satisfied [E0277]
v[j];
^~~~
note: the type `collections::vec::Vec<_>` cannot be indexed by `i32`
error: aborting due to previous error

There’s a lot of punctuation in that message, but the core of it makes sense: you cannot index with an i32.

Out-of-bounds Access

If you try to access an index that doesn’t exist:

let v = vec![1, 2, 3];
println!("Item 7 is {}", v[7]);

then the current thread will panic with a message like this:

thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 7'

If you want to handle out-of-bounds errors without panicking, you can use methods like get or get_mut that return None when given an invalid index:


# #![allow(unused_variables)]
#fn main() {
let v = vec![1, 2, 3];
match v.get(7) {
    Some(x) => println!("Item 7 is {}", x),
    None => println!("Sorry, this vector is too short.")
}
#}

Iterating

Once you have a vector, you can iterate through its elements with for. There are three versions:


# #![allow(unused_variables)]
#fn main() {
let mut v = vec![1, 2, 3, 4, 5];

for i in &v {
    println!("A reference to {}", i);
}

for i in &mut v {
    println!("A mutable reference to {}", i);
}

for i in v {
    println!("Take ownership of the vector and its element {}", i);
}
#}

Note: You cannot use the vector again once you have iterated by taking ownership of the vector. You can iterate the vector multiple times by taking a reference to the vector whilst iterating. For example, the following code does not compile.

let v = vec![1, 2, 3, 4, 5];

for i in v {
    println!("Take ownership of the vector and its element {}", i);
}

for i in v {
    println!("Take ownership of the vector and its element {}", i);
}

Whereas the following works perfectly,


# #![allow(unused_variables)]
#fn main() {
let v = vec![1, 2, 3, 4, 5];

for i in &v {
    println!("This is a reference to {}", i);
}

for i in &v {
    println!("This is a reference to {}", i);
}
#}

Rust webdev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Rust & WebAssembly para JavaScripters

A lo largo de la charla descubriremos las características más destacables de Rust, sus similitudes y diferencias con JavaScript y veremos qué aporta Rust al futuro de la Web gracias a WebAssembly. Rust es un lenguaje tipado, rápido y seguro, que ha sido diseñado por Mozilla como lenguaje de sistemas, aunque en los últimos tiempos ha ganado mucha popularidad en el terreno del desarrollo Web gracias a WebAssembly, su amplio ecosistema y gran comunidad

Rust vs. Go: Should I Rust, or Should I Go

Well both Rust and Go provide amazing performance. Should you write you’re next big thing with Rust or with Go? Go is fast and powerful, but it avoids bogging the developer down, focusing instead on simplicity and uniformity. Rust. If on the other hand, wringing out every last ounce of performance is a necessity, then Rust should be your choice. Rust is more of a competitor to C++ than it is with Go.

The Rust Programming Language - Understanding If in Rust

The Rust Programming Language - Understanding If in Rust. Rust’s take on if is not particularly complex, but it’s much more like the if you’ll find in a dynamically typed language than in a more traditional systems language. if is a specific form of a more general concept, the ‘branch’, whose name comes from a branch in a tree: a decision point, where depending on a choice, multiple paths can be taken.

The Rust Programming Language - Understanding Ownership in Rust

The Rust Programming Language - Understanding Ownership in Rust. Ownership is Rust's most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector. Ownership is how Rust achieves its largest goal, memory safety. There are a few distinct concepts, each with its own chapter: ownership, borrowing and lifetimes ...

The Rust Programming Language - Understanding Functions in Rust

The Rust Programming Language - Understanding Functions in Rust - Functions - Functions are the building blocks of readable, maintainable, and reusable code. Every Rust program has at least one function.