Основы Rust
Rust Functions and Return Values
Define functions with typed parameters and return a value without writing return.
Что вы узнаете
- Parameters with types
- Return type after ->
- The last expression is returned
area(4, 5)
- 1
4, 5arguments - 2
width * heightthe body runs - 3
20returned to the caller
Values go in, one value comes out
A function groups code under a name. In Rust you write the type of every parameter and, after ->, the type of the value the function returns.
The last expression of a function is its return value when it has no semicolon, so width * height is returned without the return keyword. format! builds a String the same way println! prints one.
Главное
- Every parameter needs a type.
- -> u32 says what the function returns.
- A final expression without ; is the return value.
Пример на Rust, который можно запустить
Rust
main.rs
fn area(width: u32, height: u32) -> u32 {
width * height
}
fn describe(name: &str, size: u32) -> String {
format!("{name} covers {size} square meters")
}
fn main() {
let size = area(4, 5);
println!("{}", describe("The room", size));
}
The room covers 20 square metersПрактика
Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.
Закончили этот урок?
Отметьте его как изученный, чтобы следить за прогрессом.
Ваш прогресс сохранён в этом браузере Войдите, чтобы он был доступен на всех устройствах.
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
- Largest of Three Pick the largest of three numbers without a built-in max. Легко
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Легко