0Pricing
Learn Rust Coding · Aula

Criando e preenchendo vetores

Crie Vecs e adicione itens com push.

Criando e preenchendo vetores é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What Is a Vector?

A vector is a growable list of values, all of the same type. Unlike a fixed-size array, a vector can shrink or grow while your program runs.

In Rust the type is written Vec<T>, where T is the type of element it holds, like Vec<i32> for integers.

An Empty Vector

You can make a fresh, empty vector with Vec::new(). Because it has no values yet, Rust cannot guess the element type, so you usually annotate it.

Here we tell Rust this vector will hold i32 integers.

fn main() {
    let v: Vec<i32> = Vec::new();
    println!("len = {}", v.len());
}

The vec! Macro

The quickest way to create a vector with starting values is the vec! macro. List the values inside square brackets.

Rust looks at the values to infer the element type, so no annotation is needed here.

fn main() {
    let nums = vec![10, 20, 30];
    println!("{:?}", nums);
}

Printing a Vector

A whole vector is printed with the debug formatter {:?}, not the normal {}. The debug form shows the values inside square brackets.

Use {:#?} for a pretty, multi-line layout when a vector is large.

fn main() {
    let names = vec!["Ann", "Bo", "Cy"];
    println!("{:?}", names);
}

Pushing Values

To add a value to the end of a vector, call push. The vector must be declared mut because pushing changes it.

Each push appends one item, growing the length by one.

fn main() {
    let mut v = Vec::new();
    v.push(1);
    v.push(2);
    v.push(3);
    println!("{:?}", v);
}

Type From the First Push

When you start with Vec::new() and no annotation, Rust waits for the first push to learn the element type.

Below, pushing 3.5 tells Rust this is a Vec<f64>. All later values must match that type.

fn main() {
    let mut prices = Vec::new();
    prices.push(3.5);
    prices.push(9.0);
    println!("{:?}", prices);
}

Filling With Repeats

The vec! macro can repeat a value. Write vec![value; count] to build a vector of that value repeated count times.

This is handy for setting up a list of zeros or default values.

fn main() {
    let zeros = vec![0; 5];
    println!("{:?}", zeros);
}

Filling in a Loop

You can fill a vector by pushing inside a loop. Here we add the squares of numbers 1 through 4.

Starting empty and pushing as you go is a common pattern when the values are computed.

fn main() {
    let mut squares = Vec::new();
    for n in 1..=4 {
        squares.push(n * n);
    }
    println!("{:?}", squares);
}

Capacity vs Length

Length is how many items a vector holds now. Capacity is how much room it has reserved before it needs to grow its memory.

If you know roughly how many items you will add, Vec::with_capacity(n) reserves space up front and avoids repeated reallocation.

fn main() {
    let mut v = Vec::with_capacity(10);
    v.push(1);
    println!("len {}, cap {}", v.len(), v.capacity());
}

From an Array

You can turn an array into a vector. One simple way is .to_vec(), which copies the array's elements into a new owned vector.

This is useful when you start with fixed data but need it to grow later.

fn main() {
    let arr = [1, 2, 3];
    let v = arr.to_vec();
    println!("{:?}", v);
}

Checking If Empty

Use is_empty() to check whether a vector has no elements. It returns a bool, which is clearer than comparing the length to zero.

This is a good guard before reading the first element.

fn main() {
    let v: Vec<i32> = Vec::new();
    if v.is_empty() {
        println!("nothing here yet");
    }
}

Quick Check

Test your understanding of creating and filling vectors.

Recap

You learned to create vectors with Vec::new() and the vec! macro, and to fill them using push, repeats, loops, and to_vec().

You also saw length versus capacity and how to check emptiness. Next you will read and loop over vector values.

Perguntas Frequentes

A aula “Criando e preenchendo vetores” é grátis?

Sim — o texto completo de “Criando e preenchendo vetores” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.

O que vou aprender em “Criando e preenchendo vetores”?

Crie Vecs e adicione itens com push. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Criando e preenchendo vetores”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Criando e preenchendo vetores
  2. Indexação e iteração
  3. Aumentando e diminuindo
  4. Vetores de structs
← Voltar para Learn Rust Coding