Tipos compostos
Tuplas e matrizes
Tipos compostos é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 3 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 Are Compound Types?
Compound types group multiple values into one. Rust has two primitive compound types:
- Tuples — fixed-size groups of possibly different types.
- Arrays — fixed-size groups of the same type.
fn main() {
let tup = (1, 2.0, 'c');
let arr = [10, 20, 30];
println!("{} {}", tup.0, arr[0]);
}Creating Tuples
A tuple bundles values inside parentheses. Each element can be a different type.
The tuple's type is the combination of its element types.
fn main() {
let person: (&str, u32, f64) = ("Alice", 30, 5.6);
println!("{} is {} years old", person.0, person.1);
}Accessing Tuple Elements
Access tuple elements by index using a dot, starting at 0.
tup.0is the first element.tup.1is the second.
fn main() {
let point = (3, 7);
let x = point.0;
let y = point.1;
println!("x={} y={}", x, y);
}Destructuring Tuples
You can break a tuple into separate variables in one step. This is called destructuring.
fn main() {
let coords = (1.5, 2.5, 3.5);
let (a, b, c) = coords;
println!("{} {} {}", a, b, c);
}The Unit Type
An empty tuple () is called the unit type. It represents 'no meaningful value'.
Functions that return nothing actually return ().
fn main() {
let nothing = ();
println!("unit value is {:?}", nothing);
}Creating Arrays
An array holds multiple values of the same type with a fixed length, written in square brackets.
Its type is [type; length].
fn main() {
let days: [&str; 3] = ["Mon", "Tue", "Wed"];
let numbers = [1, 2, 3, 4, 5];
println!("{} {}", days[1], numbers[4]);
}Array Indexing
Access array elements with square brackets and a zero-based index.
Accessing an out-of-bounds index causes a runtime panic — Rust checks bounds for safety.
fn main() {
let colors = ["red", "green", "blue"];
println!("first {}", colors[0]);
println!("last {}", colors[2]);
}Repeated Initial Values
To fill an array with the same value, use [value; count].
This creates an array of count elements all equal to value.
fn main() {
let zeros = [0; 5];
println!("{:?}", zeros);
println!("length is {}", zeros.len());
}Array Length
The .len() method returns the number of elements in an array. Length is fixed at compile time.
If you need a growable list, use a Vec instead.
fn main() {
let scores = [88, 92, 75, 100];
println!("there are {} scores", scores.len());
}Iterating an Array
Use a for loop to visit each element of an array in order.
fn main() {
let nums = [2, 4, 6, 8];
let mut sum = 0;
for n in nums {
sum += n;
}
println!("sum = {}", sum);
}Tuples vs Arrays
When to use each:
- Use a tuple for a fixed group of different types, like a coordinate plus a label.
- Use an array for a fixed group of the same type, like a list of scores.
fn main() {
let record = ("Bob", [90, 85, 95]);
println!("{} first score {}", record.0, (record.1)[0]);
}Quick Check
Choose the correct statement about Rust compound types.
Recap
Rust's compound types:
- Tuples —
(a, b, c), mixed types, accessed by.0, destructurable. - Arrays —
[a, b, c], same type, fixed length, accessed by[index]. ()is the unit type.
fn main() {
let (name, scores) = ("Cara", [70, 80, 90]);
let mut total = 0;
for s in scores {
total += s;
}
println!("{} total {}", name, total);
}Perguntas Frequentes
A aula “Tipos compostos” é grátis?
Sim — o texto completo de “Tipos compostos” é 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 “Tipos compostos”?
Tuplas e matrizes 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 3 de 4.
Quanto tempo leva a aula “Tipos compostos”?
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
- let e mutabilidade
- Tipos escalares
- Tipos compostos
- Sombreamento