Rust 函数
概述
函数是 Rust 代码的基本构建块。本章将学习函数的定义、参数、返回值、闭包等概念。
🔧 函数基础
函数定义和调用
rust
fn main() {
println!("Hello, world!");
another_function();
function_with_parameter(5);
print_labeled_measurement(5, 'h');
let x = five();
println!("The value of x is: {}", x);
let x = plus_one(5);
println!("The value of x is: {}", x);
}
fn another_function() {
println!("Another function.");
}
fn function_with_parameter(x: i32) {
println!("The value of x is: {}", x);
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {}{}", value, unit_label);
}
fn five() -> i32 {
5
}
fn plus_one(x: i32) -> i32 {
x + 1
}🔄 高阶函数
函数作为参数
rust
fn add_one(x: i32) -> i32 {
x + 1
}
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(arg) + f(arg)
}
fn main() {
let answer = do_twice(add_one, 5);
println!("The answer is: {}", answer);
}📝 本章小结
函数是 Rust 的核心概念,掌握函数的使用对编写 Rust 程序至关重要。
继续学习:下一章 - Rust 条件语句