输入输出
和 C++ 一样,都有标准的输入输出:
1 | rust复制代码use std::io::stdin; |
如果有开发经验的,或者对 C++有所了解的,这代码不能理解,一句话:就是利用标准的std::io::stdin
方法输入内如,然后把内容存入变量 your_name
中,读出,最后加上一个异常提示 expect
。
关于这个链式的写法,文中有说明:
Combining functions like this is called function chaining. Starting from the top, each function passes its results to the next function. It’s common to format a function chain with each step on its line, indented to indicate that the block belongs together.
function
将上面的代码封装成为一个函数:
1 | rust复制代码use std::io::stdin; |
其中,特别不一样的地方在于:函数中的返回,可以直接写 your_name
,省略了 return
和分号,这个有意思。
This line doesn’t end with a semicolon. This is Rust shorthand for return. Any expression may return this way. It’s the same as typing return your_name;. Clippy will complain if you type return when you don’t need it.
Array
定义数组有两个规则:
- 数据类型一致;
- 数组的长度不变
定义数组和便利数组的方法和形式,和其他语言差不多,不需要怎么去解释,如:
1 | rust复制代码let visitor_list = ["叶梅树", "叶帅", "叶哥"]; |
Structs
俗语:结构体
其中,上面我们用到的 String
和 StdIn
都是结构体类型。
我们可以定义一个结构体,然后再继承这个结构体,编写对应的结构体方法,有点类似 Swift 的写法。
如,我们定义一个 Visitor
结构体:
1 | rust复制代码// 定义一个结构体 |
使用:
1 | rust复制代码use std::io::stdin; |
Vectors
相比 Arrays,Vectors 可以动态的调整大小,利用 push
方法增加元素,直到收到系统内存的限制,或者无限增加。
其他使用方法大同小异,这里就不在描述了。
Enumerations
这个使用也差不多,没什么不同的地方,在以后使用过程中去描述使用方法。
1 | arduino复制代码enum VisitorAction { |
这里的,AcceptWithNodte { note: String }
当你使用到时,可以自定义变量使用。
对于第二章,核心的基本就这些了,第三章我们就可以进入 Game 阶段了,以上的基础知识我们可以有针对的上网查看具体使用方法。
本文转载自: 掘金