当前位置:网站首页>Rust从入门到精通06-函数
Rust从入门到精通06-函数
2022-08-11 08:16:00 【51CTO】
1、函数简介
①、Rust 的函数使用关键字 fn 开头,函数名称使用snake case规范风格(所有字母小写并使用下划线分隔);
②、可以有一系列的输入参数,可以有一个返回值;
③、函数返回可以使用 return 语句,也可以使用表达式(末尾不带分号);
④、函数也可以不写返回类型,这种情况下,编译器会认为返回类型是unit();
⑤、可执行程序的入口是 fn main();
⑥、调用函数时,Rust不关心函数定义在哪(前后都无所谓),只要定义了就行;
⑦、Rust 函数体内可以定义其它模块,比如静态变量、常量、函数、trait、类型等。
2、函数实例
3、函数返回值
需要注意语句和表达式的区别,表达式没有分号,有返回值。语句结尾有分号,没有返回值。
所以对于如下函数,如果函数体加上分号,则会报错:
把 x+y; 变成表达式即可(去掉末尾的分号)。
4、发散函数
Rust 支持一种特殊的发散函数(Diverging functions),它的返回类型是感叹号 !。 如果一个函数根本就不能正常返回,那么它就可以这样写:
发散函数的最大特点:可以被转换成任意一个类型。
在Rust 中,有下列情况返回类型都是 !:
1.panic! 以及基于它实现的各种函数/宏,比如unimplemented!、unreachable! 2.死循环loop{} 3.进程退出函数std::process::exit以及类似的libc 中的exec一类函数。
5、const fn
函数可以用 const 关键字修饰,这样的函数可以在编译阶段被编译器执行,返回值也被视为编译期常量。
需要注意的是:const 函数是在编译阶段执行的,因此相比普通函数有很多限制,并非所有的表达式和语句都可以在其中使用。
而且这个功能还没有完全稳定。
边栏推荐
- The growth path of a 40W test engineer with an annual salary, which stage are you in?
- Analysys and the Alliance of Small and Medium Banks jointly released the Hainan Digital Economy Index, so stay tuned!
- About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
- For the first time, I suspect that there is a bug in selenium4 because the iframe element is not found?
- Kotlin算法入门计算质因数
- C Primer Plus(6) 中文版 第1章 初识C语言 1.7 使用C语言的7个步骤
- Swagger简单使用
- golang string manipulation
- AcWing 272. 最长公共上升子序列
- 支持各种文件快速重命名最简单的小技巧
猜你喜欢
Active users of mobile banking grew rapidly in June, hitting a half-year high
JUC Concurrent Programming
1.1-Regression
机器学习(三)多项式回归
The growth path of a 40W test engineer with an annual salary, which stage are you in?
【LeetCode】链表题解汇总
如何通过 IDEA 数据库管理工具连接 TDengine?
1061 True or False (15 points)
1076 Wifi Password (15 points)
Conditional statements in TF; where()
随机推荐
《剑指offer》题解——week3(持续更新)
1036 Programming with Obama (15 points)
Use tf.argmax in Tensorflow to return the index of the maximum value of the tensor along the specified dimension
零基础SQL教程: 基础查询 05
TF generates (feature, label) set through feature and label, tf.data.Dataset.from_tensor_slices
go sqlx 包
IQUNIX A80 exploring TTC金粉 初体验
Conditional statements in TF; where()
分布式锁-Redission - 缓存一致性解决
装饰器模式:Swift 实现
Kotlin Algorithm Getting Started with Rabbit Number Optimization and Expansion
Kotlin算法入门求回文数数算法优化二数字生成规则
opengauss创建用户权限问题
Square, multi-power, square root calculation in Tf
Evolution and New Choice of Streaming Structured Data Computing Language
Kotlin算法入门求完全数
Kotlin算法入门求自由落体
法律顾问成了律所鸡肋产品了吗?
Four operations in TF
1076 Wifi Password (15 points)