01. 语法基础
语法基础
fn main() {
print!("Hello, world!");
}
;
,我们将创建另一个函数。首先,主要是打印数字
fn main() {
println!("Hello, world number {}!", 8);
}
Hello, world number 8!
。我们可以放更多:
fn main() {
println!("Hello, worlds number {} and {}!", 8, 9);
}
下面我们可以创建新的函数:
fn main() {
println!("Hello, world number {}!", number());
}
fn number() -> i32 {
8
}
函数内部只有;
,所以它是返回的值。如果带有;
,则不会返回任何内容。如果有 ;
,()
,而不是
fn main() {
println!("Hello, world number {}", number());
}
fn number() -> i32 {
8; // ⚠️
}
5 | fn number() -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
6 | 8;
| - help: consider removing this semicolon
这意味着“您告诉我return 8;
但是在;
回来。要为函数提供变量时,请将其放在
fn main() {
multiply(8, 9); // We can give the numbers directly
let some_number = 10; // Or we can declare two variables
let some_other_number = 2;
multiply(some_number, some_other_number); // and put them in the function
}
fn multiply(number_one: i32, number_two: i32) { // Two i32s will enter the function. We will call them number_one and number_two.
let result = number_one * number_two;
println!("{} times {} is {}", number_one, number_two, result);
}
当然,我们也可以返回一个
fn main() {
let multiply_result = multiply(8, 9); // We used multiply() to print and to give the result to multiply_result
}
fn multiply(number_one: i32, number_two: i32) -> i32 {
let result = number_one * number_two;
println!("{} times {} is {}", number_one, number_two, result);
result // this is the i32 that we return
}