2.3 Rust函数
2.3 函数
[root@itoracle src]# cargo new functions
Created binary (application) `functions` package
[root@itoracle src]# cd functions/
[root@itoracle functions]# vim src/main.rs
Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscores separate words. Here’s a program that contains an example function definition:
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
Rust doesn’t care where you define your functions, only that they’re defined somewhere.
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/goapp/src/functions)
Finished dev [unoptimized + debuginfo] target(s) in 6.41s
Running `target/debug/functions`
Hello, world!
Another function.
函数参数
In function signatures, you must declare the type of each parameter. This is a deliberate decision in Rust’s design: requiring type annotations in function definitions means the compiler almost never needs you to use them elsewhere in the code to figure out what you mean.
fn main() {
another_function(5, 6);
}
fn another_function(x: i32, y: i32) {
println!("The value of x is: {}", x);
println!("The value of y is: {}", y);
}
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/goapp/src/functions)
Finished dev [unoptimized + debuginfo] target(s) in 3.03s
Running `target/debug/functions`
The value of x is: 5
The value of y is: 6
函数体
Function bodies are made up of a series of statements optionally ending in an expression.
We’ve actually already used statements and expressions. Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.
Creating a variable and assigning a value to it with the let keyword is a statement. let y = 6; is a statement.
fn main() {
let y = 6;
}
Function definitions are also statements; the entire preceding example is a statement in itself.
Statements do not return values. Therefore, you can’t assign a let statement to another variable, as the following code tries to do; you’ll get an error:
fn main() {
let x = (let y = 6);
}
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/goapp/src/functions)
error: expected expression, found statement (`let`)
--> src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^ expected expression
|
= note: variable declaration using `let` is a statement error: aborting due to previous error error: Could not compile `functions`. To learn more, run the command again with --verbose.
The let y = 6 statement does not return a value, so there isn’t anything for x to bind to.
Expressions evaluate to something and make up most of the rest of the code that you’ll write in Rust. Consider a simple math operation, such as 5 + 6, which is an expression that evaluates to the value 11.Expressions can be part of statements: The 6 in the statement let y = 6; is an expression that evaluates to the value 6. Calling a function is an expression. Calling a macro is an expression. The block that we use to create new scopes, {}, is an expression, for example
fn main() {
let _x = 5;
let _y = {
let _x = 3;
_x + 1
};
println!("The value of y is: {}", _y);
}
let y = {
let x = 3;
x + 1
};
is a block that, in this case, evaluates to 4. That value gets bound to y as part of the letstatement. Note the x + 1 line without a semicolon at the end, which is unlike most of the lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value. Keep this in mind as you explore function return values and expressions next.
[root@itoracle functions]# cargo run src/main.rs
Compiling functions v0.1.0 (/usr/local/automng/src/goapp/src/functions)
Finished dev [unoptimized + debuginfo] target(s) in 0.63s
Running `target/debug/functions src/main.rs`
The value of y is: 4
函数返回值
We don’t name return values, but we do declare their type after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly. Here’s an example of a function that returns a value:
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {}", x);
}
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/rust/test/functions)
Finished dev [unoptimized + debuginfo] target(s) in 4.96s
Running `target/debug/functio
There are two important bits: first, the line let x = five(); shows that we’re using the return value of a function to initialize a variable. Because the function five returns a 5, that line is the same as the following:
let x = 5;
Second, the five function has no parameters and defines the type of the return value, but the body of the function is a lonely 5 with no semicolon because it’s an expression whose value we want to return.
fn main() {
let x = plus_one(5);
println!("The value of x is: {}", x);
}
fn plus_one(x: i32) -> i32 {
x + 1
}
注意,函数体结束的时候没有分号“;”
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/rust/test/functions)
Finished dev [unoptimized + debuginfo] target(s) in 1.76s
Running `target/debug/functions`
The value of x is: 6
如果不是在函数体最后一行返回,则可以使用return语句
fn main() {
let mut x = plus_one(5);
println!("The value of x is: {}", x);
x = plus_one(15);
println!("The value of x is: {}", x);
}
fn plus_one(mut x: i32) -> i32 {
if x < 10 {
return 10;
}
x = x + 10;
x
}
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/rust/test/functions)
Finished dev [unoptimized + debuginfo] target(s) in 1.22s
Running `target/debug/functions`
The value of x is: 10
The value of x is: 25
另外,最后一句使用return语句也是可以的,但rust建议使用不加分号的表达式
fn main() {
let mut x = plus_one(5);
println!("The value of x is: {}", x);
x = plus_one(15);
println!("The value of x is: {}", x);
}
fn plus_one(mut x: i32) -> i32 {
if x < 10 {
return 10;
}
x = x + 10;
return x;
}
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/rust/test/functions)
Finished dev [unoptimized + debuginfo] target(s) in 2.43s
Running `target/debug/functions`
The value of x is: 10
The value of x is: 25
没有返回值的函数
fn justgo(){
println!("永远是多远?");
}
[root@itoracle functions]# cat src/main.rs
fn main() {
let mut x = plus_one();
println!("The value of x is: {}", x);
x = plus_one();
println!("The value of x is: {}", x);
justgo();
} fn plus_one(mut x: i32) -> i32 {
if x < {
return ;
}
x = x + ;
x
} fn justgo(){
println!("永远是多远?");
}
运行结果
[root@itoracle functions]# cargo run
Compiling functions v0.1.0 (/usr/local/automng/src/rust/test/functions)
Finished dev [unoptimized + debuginfo] target(s) in .95s
Running `target/debug/functions`
The value of x is:
The value of x is:
永远是多远?
函数定义后,必须被调用,不然运行时会给出警告
warning: function is never used: `justgo`
--> src/main.rs::
|
| fn justgo(){
| ^^^^^^^^^^^ Finished dev [unoptimized + debuginfo] target(s) in .48s
Running `target/debug/functions`
使用元组让函数返回多个值
fn testFnReturn() -> (u8,String){
(,"good".to_string())
}
let a = testFnReturn();
println!("{}",a.);
2.3 Rust函数的更多相关文章
- rust 函数-生命周期
记录一下自己理解的生命周期. 每个变量都有自己的生命周期. 在c++里生命周期好比作用域, 小的作用域的可以使用大作用域的变量. 如果把这里的每个作用域取个名,那么就相当于rust里的生命周期注解. ...
- rust 函数的使用
fn main() { println!("Hello, world!"); another_function(2,3); let y ={ let x =3; //表达式的结尾没 ...
- Rust <2>:函数、方法与注释的格式
rust 函数定义格式如下: fn function_name(a: i64, b: u32, c: bool) -> (d: f64, e: &str) { ... (1, " ...
- Rust笔记
前言: 学了有段时间了,现在同步到博客园. 正文: Rust语言介绍 l Rust由js之父开发的新型语言,打破了传统的难以接触底层的局面.这是个有C++开发的语言.拥有C的血统 l Rust必须严格 ...
- Rust到底值不值得学--Rust对比、特色和理念
前言 其实我一直弄不明白一点,那就是计算机技术的发展,是让这个世界变得简单了,还是变得更复杂了. 当然这只是一个玩笑,可别把这个问题当真. 然而对于IT从业者来说,这可不是一个玩笑.几乎每一次的技术发 ...
- Rust学习笔记1
这是一份不错的rust教程,目前包括4个block和4个project.全部完成后可以用rust实现一个简单的key-value存储引擎. 注意:Windows下rust貌似会遇到一些bug,强烈建议 ...
- 【译】Rust宏:教程与示例(二)
原文标题:Macros in Rust: A tutorial with examples 原文链接:https://blog.logrocket.com/macros-in-rust-a-tutor ...
- Rust安装-运行第一个程序-hello_world
Rust官网:https://rust-lang.org/ 安装 点击install,选择版本 选择相对应的版本进行下载 我这里下载的是windows系统,运行下载好的exe文件,根据需要选择选对应的 ...
- FinClip小程序+Rust(三):一个加密钱包
一个加密货币钱包,主要依赖加密算法构建.这部分逻辑无关iOS还是Android,特别适合用Rust去实现.我们看看如何实现一个生成一个模拟钱包,准备供小程序开发采用 前言 在之前的内容我们介绍了整 ...
随机推荐
- Node.js的__dirname,__filename,process.cwd(),./的含义
简单说一下这几个路径的意思,: __dirname: 获得当前执行文件所在目录的完整目录名 __filename: 获得当前执行文件的带有完整绝对路径的文件名 process.cwd():获得当前执行 ...
- windows VS2013 编译安装QWT6.1和QWTPolar1.1.1
QWT的编译和配置 1. 下载QWT从官网 For getting a snapshot with all bugfixes for the latest 5.2 release: svn expor ...
- oracle date 和 timestamp区别
在今天的工作中,学到了以下几个知识点: 一.date和timestamp 的区别 date类型是Oracle常用的日期型变量,他的时间间隔是秒.两个日期型相减得到是两个时间的间隔,注意单位是“天”.例 ...
- C指针的解析
这是我从网上转载的一篇关于C指针的文章,方便自己以后回顾,自己添加修改部分内容 ,不对请指正 Attention:指针是指针变量 ,数组是指针常量 第一章 指针的概念 指针是一个特殊的变量,它里面存 ...
- mvvm模式下在WPF项目中动态加载项目的程序集和类
在mvvm模式的wpf项目中有个需求需要去加载解决方案的程序集,并且根据程序集去动态加载当前程序集的类,做成下拉框形式. 效果: //全局定义 private ComboBox abList= nul ...
- 十天入门java教程 Day01
这几年一直在想学一门语言,java,Python,php也都看过,但是没有一门是精的.语言学习并不是写出hello world就行了.个人感觉需要静心去学习. java语言是什么? java是一种计算 ...
- js setTime()详解
来源:http://www.jb51.net/article/35535.htm#t1 setTimeout setTimeout 语法例子 用 setTimeout 来执行 function 不断重 ...
- pch文件的创建与配置
1.ios中pch文件的创建与配置 1.1 ios中pch文件的创建与配置 1.2 全局宏定义标志的配置 2.宏定义 这里放的主要是开发中常用的宏定义. /** 动态的字符串格式化宏 */ #defi ...
- hdu4651(广义五边形数 & 分割函数1)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4651 题意:f(x) 为将 x 分成其他数和的形式的方案数.对于 t 组输入,输出 f(xi). 思路 ...
- 分数规划-poj3111
题意:给定n个珠宝,每个珠宝有重量 w 和价值v ,要求你从中选出k个,使∑v/∑w 尽可能大,输出选出的珠宝的编号 数据范围: 1 ⩽ k ⩽ n ⩽ 10 , 1 ⩽ w , v ⩽ 10. 这道 ...