Tuples, arrays and functions
So far you have worked with single values. Compound types group several values into one. Rust has two primitive compound types: tuples, which mix different types, and arrays, which store elements of the same type with a fixed size. After that you will learn to write functions, the tool to name a piece of logic and reuse it, and a key idea in Rust: almost everything is an expression that produces a value.
Tuples
A tuple is written in parentheses with values separated by commas. Each position can have a different type, and the full type is the list of types, for example (i32, f64, char). You access an element with a dot and its position (t.0, t.1) or you break the tuple into variables with a pattern (destructuring). The empty tuple () is called unit and is what a function returns when it returns nothing. Use tuples to group a few related values; when you start needing names, you will learn structs in week 4.
fn main() {
let person: (&str, u32, f64) = ("Ana", 30, 1.68);
println!("{} is {} years old", person.0, person.1);
let (name, age, height) = person; // destructuring
println!("{name} / {age} / {height}");
let unit = ();
println!("{:?}", unit);
}Arrays
An array has all its elements of the same type and a length that is part of the type: [i32; 5] is different from [i32; 6]. It lives on the stack and it neither grows nor shrinks. To repeat a value you write [0; 10], which creates ten zeros. You access it with brackets and an index that starts at 0. If the index is out of range, Rust does not read foreign memory like other languages could: the program panics and stops with a clear message. When you need a collection that grows you will use Vec, in week 5.
fn main() {
let months = ["Jan", "Feb", "Mar"];
let zeros = [0; 4];
let nums: [i32; 3] = [10, 20, 30];
println!("{} {:?} {:?}", months[0], zeros, nums);
println!("length = {}", nums.len());
let index = nums.len() + 4;
// Panics at runtime: index out of bounds (len is 3)
println!("{}", nums[index]);
}Functions
Functions are declared with fn, a name in snake_case, parameters with a mandatory type and, if they return something, an arrow -> followed by the type. The body is a block. Rust distinguishes statements (they do something and return no value, like let x = 1;) from expressions (they evaluate to a value, like x + 1). The last expression of a block, without a semicolon, is the value the function returns; you can also use return to exit early.
fn add(a: i32, b: i32) -> i32 {
a + b // no semicolon: this is the return value
}
fn min_max(values: [i32; 4]) -> (i32, i32) {
let mut min = values[0];
let mut max = values[0];
for v in values {
if v < min { min = v; }
if v > max { max = v; }
}
(min, max)
}
fn main() {
println!("{}", add(2, 3));
let (lo, hi) = min_max([4, -2, 9, 0]);
println!("min = {lo}, max = {hi}");
let y = {
let x = 3;
x + 1 // a block is an expression
};
println!("y = {y}");
}// This does NOT compile on purpose: the semicolon turns the value into ()
fn add(a: i32, b: i32) -> i32 {
a + b;
}
fn main() {
println!("{}", add(1, 2));
}Parameters always carry a type, even though the compiler can infer almost everything else inside the body. This is a design decision: a function signature is a contract, and writing it clearly helps both the reader and the error messages. To return several values, the usual solution is a tuple, as min_max does. Notice also that main is just another function: it is the entry point and takes no parameters.
اختبر ما تعلمته
السؤال 1 من 5How do you access the second element of tuple t?
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف