Rust 代码中的函数和变量名利用 snake case 规范风格。在 snake case 中,全部字母都是小写并利用下划线分隔单词。这是一个包含函数定义示例的程序:- fn main() {
- println!("Hello, world!");
- another_function();
- }
- fn another_function() {
- println!("Another function.");
- }
复制代码 Rust 不关心函数定义所在的位置,只要函数被调用时出现在调用之处可见的作用域内就行。
运行上面的代码,得到输出:- $ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
- Running `target/debug/functions`
- Hello, world!
- Another function.
复制代码 参数
当函数拥有参数(形参)时,可以为这些参数提供具体的值(实参)
在函数签名中,必须 声明每个参数的类型。
要求在函数定义中提供类型注解,意味着编译器再也不必要你在代码的其他地方注明类型来指出你的意图。而且,在知道函数必要什么类型后,编译器就能够给出更有用的错误消息。
当定义多个参数时,利用逗号分隔- fn main() {
- another_function(5);
- }
- fn another_function(x: i32) {
- println!("The value of x is: {x}");
- }
复制代码 运行后得到输出- $ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.21s
- Running `target/debug/functions`
- The value of x is: 5
复制代码 语句和表达式
语句(Statements)是执行一些操作但不返回值的指令。 表达式(Expressions)计算并产生一个值。
函数定义也是语句
语句不返回值。因此,不能把 let 语句赋值给另一个变量
表达式的结尾没有分号
如果在表达式的结尾加上分号,它就变成了语句,而语句不会返回值。
具有返回值的函数
函数可以向调用它的代码返回值。我们并不对返回值命名,但要在箭头(->)后声明它的类型。在 Rust 中,函数的返回值等同于函数体最后一个表达式的值。利用 return 关键字和指定值,可从函数中提前返回;但大部分函数隐式的返回最后的表达式。这是一个有返回值的函数的例子:- fn five() -> i32 {
- 5
- }
- fn main() {
- let x = five();
- println!("The value of x is: {x}");
- }
复制代码 在 five 函数中没有函数调用、宏、乃至没有 let 语句 —— 只有数字 5。这在 Rust 中是一个完全有效的函数。注意,也指定了函数返回值的类型,就是 -> i32。尝试运行代码;输出应该看起来像这样:- $ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
- Running `target/debug/functions`
- The value of x is: 5
复制代码 另一个例子:- fn main() {
- let x = plus_one(5);
- println!("The value of x is: {x}");
- }
- fn plus_one(x: i32) -> i32 {
- x + 1;
- }
复制代码 运行代码会产生一个错误,如下:- $ cargo run
- Compiling functions v0.1.0 (file:///projects/functions)
- error[E0308]: mismatched types
- --> src/main.rs:7:24
- |
- 7 | fn plus_one(x: i32) -> i32 {
- | -------- ^^^ expected `i32`, found `()`
- | |
- | implicitly returns `()` as its body has no tail or `return` expression
- 8 | x + 1;
- | - help: remove this semicolon to return this value
- For more information about this error, try `rustc --explain E0308`.
- error: could not compile `functions` (bin "functions") due to 1 previous error
复制代码 函数 plus_one 的定义说明它要返回一个 i32 类型的值,不外语句并不会返回值,利用单位类型 () 表示不返回值。因为不返回值与函数定义相抵牾,从而出现一个错误。在输出中,Rust 提供了一条信息,可能有助于改正这个错误:它建议删除分号,这会修复这个错误。
表达式的结尾没有分号
如果在表达式的结尾加上分号,它就变成了语句,而语句不会返回值。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |