Exercícios de Rust

Fibonacci Sequence in Rust

Build the Fibonacci numbers with a loop, a tuple swap and a vector.

  • Iniciante
  • 2 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • A loop with two variables
  • (a, b) = (b, a + b)
  • Why u64
The first numbers
00
11
12
23
34
55
5 = 2 + 3

Each number is the sum of the two before

Each Fibonacci number is the sum of the two before it, starting from 0 and 1. Build the first numbers of the sequence in a vector.

a and b hold two neighbouring numbers. (a, b) = (b, a + b) moves both one step forward in a single assignment. u64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.

Pontos-chave

  1. Start from 0 and 1.
  2. One tuple assignment moves both values.
  3. u64 holds much larger numbers than u32.

Exemplo executável de Rust

Rust
Executar código →
main.rs
fn fibonacci(count: usize) -> Vec<u64> {
    let mut sequence = Vec::with_capacity(count);
    let (mut a, mut b) = (0u64, 1u64);
    for _ in 0..count {
        sequence.push(a);
        (a, b) = (b, a + b);
    }
    sequence
}

fn main() {
    println!("{:?}", fibonacci(10));
    println!("50th: {}", fibonacci(50)[49]);
}
Gerar um botão Run para este exemplo Resultado da execução
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
50th: 7778742049

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios