Функции и управление потоком выполнения
Научитесь определять функции и использовать выражения `if`/`else`, `loop`, `while` и `for` для управления потоком выполнения программы.
«Функции и управление потоком выполнения» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 3 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 3 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What are Functions?
Functions are named blocks of code that perform a specific task. They are fundamental for organizing your code and making it reusable.
- Code Reusability: Write a piece of logic once and use it multiple times.
- Modularity: Break down complex problems into smaller, manageable parts.
- Readability: Give meaningful names to blocks of code, improving understanding.
Your First Rust Function
In Rust, you define a function using the fn keyword. The main function is the entry point of every Rust program.
Here's how to declare and call a simple function:
fn say_hello() {
println!("Hello from a function!");
}
fn main() {
say_hello(); // Call the function
println!("Back in main.");
}Functions with Parameters
Functions can accept input values called parameters. These allow your function to operate on different data each time it's called.
Parameters are defined with a name and a type, separated by a colon.
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Alice");
greet("Bob");
}Functions with Return Values
Functions can also return a value to the caller. You specify the return type after an arrow (->).
The last expression in the function body is implicitly returned. No semicolon needed for the return expression!
fn add_numbers(x: i32, y: i32) -> i32 {
x + y // No semicolon: this expression is returned
}
fn main() {
let sum = add_numbers(5, 7);
println!("The sum is: {}", sum);
}Making Decisions: `if`/`else`
The if expression allows your program to execute different code blocks based on a condition. Conditions must always be a bool (true/false).
- Use
iffor the first condition. - Use
else iffor additional conditions. - Use
elsefor a fallback if no other conditions are met.
Rust's if is an expression, meaning it can return a value!
If-Else Expressions in Action
Here's how you can use if and else to assign a value based on a condition. Notice how it behaves like a ternary operator from other languages.
fn main() {
let number = 7;
let message = if number < 10 {
"Small number"
} else {
"Large number"
};
println!("The number is: {}", message);
let other_num = 15;
if other_num % 2 == 0 {
println!("{} is even", other_num);
} else {
println!("{} is odd", other_num);
}
}Repeating Code: `loop`
The loop keyword creates an infinite loop. This is useful when you need to repeat an action until you explicitly decide to stop.
Use break to exit the loop. You can even return a value from a loop expression using break.
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Break and return a value
}
};
println!("The result is {}", result);
}Conditional Repetition: `while`
The while loop executes a block of code as long as a specified condition remains true. It's perfect for when you don't know exactly how many times you need to loop.
fn main() {
let mut count = 3;
while count != 0 {
println!("{}!", count);
count -= 1;
}
println!("LIFTOFF!!!");
}Iterating with `for` Loops
The for loop is used to iterate over a collection of items or a range of numbers. It's Rust's most common looping construct, making your code safe and concise.
- It's often used with ranges (e.g.,
1..4for 1, 2, 3 or1..=4for 1, 2, 3, 4). - It works with any type that implements the
Iteratortrait.
fn main() {
// Loop through a range
for number in 1..4 { // 1, 2, 3
println!("Number: {}", number);
}
// Loop through an array
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("The value is: {}", element);
}
}Control Flow Challenge
Consider the following Rust code. What will be the final value of result?
fn calculate_value(input: i32) -> i32 {
if input > 10 {
input * 2
} else if input == 5 {
input + 5
} else {
input
}
}
fn main() {
let result = calculate_value(5);
// What is result?
}Functions & Control Flow Recap
You've mastered the building blocks for dynamic programs!
- Functions: Organize and reuse code using
fn, parameters, and return values. if/else: Make decisions and conditionally execute code. Remember it's an expression!loop: Create infinite loops, exit withbreak, and return values.while: Loop as long as a condition is true.for: Iterate safely over collections and ranges.
These tools are essential for writing structured and efficient Rust programs!
Часто задаваемые вопросы
Урок «Функции и управление потоком выполнения» бесплатный?
Да — полный текст урока «Функции и управление потоком выполнения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 3 уроков всего.
Чему я научусь в уроке «Функции и управление потоком выполнения»?
Научитесь определять функции и использовать выражения `if`/`else`, `loop`, `while` и `for` для управления потоком выполнения программы. Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Learn Rust Coding?
Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 3.
Сколько времени занимает урок «Функции и управление потоком выполнения»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Learn Rust Coding?
Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Переменные, изменяемость и затенение
- Примитивные типы данных и операторы
- Функции и управление потоком выполнения