学习rust概念,包含变量,数据类型和函数.
学习目标
在这个模块中你可以学到:
- 探索rust核心概念,包含函数,数据类型和变量
- 了解rust基本类型,文本,数值,布尔,和复杂类型
- 创建,编译和运行rust基本程序
- 知道自私从你程序中打印输出
需要前题
rust开发环境
介绍
在这个模块中,可以学到编程语言的基本概念,可以发现他们在rust中是怎么实现的.这些概念不是rust独有的,但他们是每个rust程序的基础.通过了解这些概念,你可以获得了解,来对任何语言的开发都有帮助.
了解rust程序的基本程序结构
在这个单元中,可以复习非常简单的rust程序结构
Rust中的函数
函数是一块代码,可以指定任务. 我们在程序中基于任务切分代码. 这样的切分使代码更容易理解和维护. 当我们为任务定义函数后,就可以在需要时调用函数来执行任务.
每个Rust程序一定名为main的函数.main函数中的代码总是第一个运行的.我们可以调用函数从main函数中,或是从其它函数中.
fn main() {
println!("Hello, world!");
}
为在rust中定义函数,需要使用fn关键字.当给函数命名后,我们可以告诉编译器多少个输入参数.参数在括号()中列出来. 函数体是函数做任务的代码,定义在大括号{}内.最佳格式化实践是打开大括号{和参数列表是同行.
代码排版
在函数体内,代码的声明以分号结尾;. rust处理这些声明按顺序一个接一个. 当代码声明后没有;时,rust知道下一行代码执行之前,开始的语句一定要先完成.
为了查看代码执行关系,我们用缩近.这种格式表示代码是怎么组织的,并且揭露了完成任务的函数流步骤. 开始的代码语句用左边4个空格. 当代码没有用;结束时,下一行用超过4个空格.
下边是对应例子
fn main() { // The function declaration is not indented
// First step in function body
// Substep: execute before First step can be complete
// Second step in function body
// Substep A: execute before Second step can be complete
// Substep B: execute before Second step can be complete
// Sub-substep 1: execute before Substep B can be complete
// Third step in function body, and so on...
}
todo! 宏
当你在rust模块中练习时,可能会注意到简单的例子中使用到了todo!宏.宏在rust中像函数,也用到输入参数.todo!宏被用来定义在rust未完成的代码.宏可以在原型开发,或是当你表示一个你未完成的操作时非常有用.
下边展示怎么用todo!:
fn main() {
// Display the message "Hello, world!"
todo!("Display the message by using the println!() macro");
}
在编译时,使用到了todo!宏,编译器需要返回panic消息,并指定希望完成代码位置.
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/playground`
thread 'main' panicked at 'not yet implemented: Display the message by using the println!() macro', src/main.rs:3:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The println! macro
main函数只做一个任务. 调用println!宏,它在rust中提前定义.println!宏接收更多输入参数, 它展示在屏幕,并且标准输出.在这个例子中,我们转入一个字符串"Hello, world!"
fn main() {
// Our main function does one task: show a message
// println! displays the input "Hello, world!" to the screen
println!("Hello, world!");
}
{}参数替换数值
通常调用println!宏用参数列表,列表中包括文本字符串实例和{}还有其它值.println!宏替换实例{}中文本字符串有,列表中下一个值.
例子:
fn main() {
// Call println! with three arguments: a string, a value, a value
println!("The first letter of the English alphabet is {} and the last letter is {}.", 'A', 'Z');
}
调用println!宏用三个个参数,字符串,值和其它值.宏处理参数是按顺序的.每个{}实例内部用一个文本字符串来替换,这些值是依次用列表参数.
输出:
The first letter of the English alphabet is A and the last letter is Z.
这篇博客介绍了Rust编程语言的基本概念,包括变量、数据类型和函数的使用。读者将学习到Rust中的函数定义,如何创建和运行基础程序,以及如何利用println!宏进行输出。文章还提到了代码格式化和todo!宏的用途,帮助初学者理解Rust程序的结构和流程。
788

被折叠的 条评论
为什么被折叠?



