rust语言 怎么经典地比较两个枚举值是否相同

Rust官方指南摘抄(一)语法基础 - 推酷
Rust官方指南摘抄(一)语法基础
1、Rust是一个静态类型语言,但是包含类型推断特性;Rust is a statically typed language, which means that we specify our types up front. So why does our first example compile? Well, Rust has this thing called “type inference.” If it can figure out what the type of something is, Rust doesn’t require you to actually type it out.
2、变量默认是不可改变的;By default, bindings are immutable. This code will not compile:
let x = 5i;
It will give you this error:
error: re-assignment of immutable variable `x`
If you want a binding to be mutable, you can use mut:
let mut x = 5i;
There is no single reason that bindings are immutable by default, but we can think about it through one of Rust’s primary focuses: safety.
表达式VS声明
1、rust里面只有2种声明:let和“表达式声明”,其它的东西都是表达式(意味着有返回值)。So what’s the difference? Expressions return a value, and statements do not. In many languages, if is a statement, and therefore, let x = if … would make no sense. But in Rust, if is an expression, which means that it returns a value. We can then use this value to initialize the binding.
2、对变量重新赋值也是表达式,但是和C不同,它的值并不是给变量的新值;Note that assigning to an already-bound variable (e.g. y = 5i) is still an expression, although its value is not particularly useful. Unlike C, where an assignment evaluates to the assigned value (e.g. 5i in the previous example), in Rust the value of an assignment is the unit type () (which we’ll cover later).
3、在一个表达式后面加一个分号就会让rust抛弃它的值,使之变成一个“表达式声明”;The semicolon turns any expression into a statement by throwing away its value and returning unit instead.
4、unit类型是一种rust特有的一种并不常用的类型,它的表示是()。“表达式声明”会返回这种类型;
1、方法声明如下:
fn print_sum(x: int, y: int) {
println!(&sum is: {}&, x + y);
2、方法参数不会做类型推导,必须显式声明类型;
Unlike let, you must declare the types of function arguments.
This is a deliberate design decision. While full-program inference is possible, languages which have it, like Haskell, often suggest that documenting your types explicitly is a best-practice. We agree that forcing functions to declare types while allowing for inference inside of function bodies is a wonderful sweet spot between full inference and no inference.
3、带返回值的方法,rust只允许返回一个值。注意最后不能加分号,那会使得表达式变成声明,从而返回值会变成()。
fn add_one(x: int) -& int {
4、rust当然也支持return关键字显式返回;
fn foo(x: int) -& int {
if x & 5 { }
return x + 1;
1、rust支持普通的行注释。如下:
// Line comments are anything after '//' and extend to the end of the line.
let x = 5i; // this is also a line comment.
// If you have a long explanation for something, you can put line comments next
// to each other. Put a space between the // and your comment so that it's
// more readable.
2、rust支持“文档注释”,用///表示,支持Markdown语法。可以用rustdoc导出成HTML等格式。如下:
/// `hello` is a function that prints a greeting that is personalized based on
/// the name given.
/// # Arguments
/// * `name` - The name of the person you'd like to greet.
/// # Example
/// ```rust
/// let name = &Steve&;
/// hello(name); // prints &Hello, Steve!&
fn hello(name: &str) {
println!(&Hello, {}!&, name);
复合数据类型
1、元组是一组相同或不同类型的数据的集合。Tuples are an ordered list of a fixed size. Like this:
let x = (1i, &hello&);
The parenthesis and commas form this two-length tuple. Here's the same code, but with the type annotated:
let x: (int, &str) = (1, &hello&);
2、元组可以通过let来取值。
let (x, y, z) = (1i, 2i, 3i);
println!(&x is {}&, x);
3、两个元组只有个数、类型、值全部相等时,才相等。
4、元组可以用来让函数返回多个值。
fn next_two(x: int) -& (int, int) { (x + 1i, x + 2i) }
fn main() {
let (x, y) = next_two(5i);
println!(&x, y = {}, {}&, x, y);
1、结构体就是元组的每个元素都给取了一个名字。存取方法如下。
struct Point {
fn main() {
let origin = Point { x: 0i, y: 0i };
println!(&The origin is at ({}, {})&, origin.x, origin.y);
2、结构体命名建议首字母大写,骆驼命名法;
3、默认不能改,除非使用mut关键字;
元组结构体
1、元组结构体就是整个结构体有名字,但里面的元素没有名字的一种类型。是结构体的简化版本,不常用。
Tuple structs do have a name, but their fields don't:
struct Color(int, int, int);
struct Point(int, int, int);
These two will not be equal, even if they have the same values:
= Color(0, 0, 0);
let origin = Point(0, 0, 0);
2、Guide说下面这种情况下元组结构体就很有用,但我没看懂有用在哪。
struct Inches(int);
let length = Inches(10);
let Inches(integer_length) =
println!(&length is {} inches&, integer_length);
1、枚举是Rust中非常有用的一个特性,在Rust标准库中被广泛使用。比如下面这个标准库提供的枚举变量。
enum Ordering {
//An Ordering can only be one of Less, Equal, or Greater at any given time. Here's an example:
fn cmp(a: int, b: int) -& Ordering {
if a & b { Less }
else if a & b { Greater }
else { Equal }
fn main() {
let x = 5i;
let y = 10i;
let ordering = cmp(x, y);
if ordering == Less {
println!(&less&);
} else if ordering == Greater {
println!(&greater&);
} else if ordering == Equal {
println!(&equal&);
2、枚举里面可以放一个可变的值。This enum has two variants, one of which has a value:
enum OptionalInt {
Value(int),
fn main() {
let x = Value(5);
Value(n) =& println!(&x is {:d}&, n),
=& println!(&x is missing!&),
Value(n) =& println!(&y is {:d}&, n),
=& println!(&y is missing!&),
3、枚举也可以这样放下多个值
enum OptionalColor {
Color(int, int, int),
1、Match是用来解决其他语言中Switch()的问题的,但更强大。
let x = 5i;
1 =& println!(&one&),
2 =& println!(&two&),
3 =& println!(&three&),
4 =& println!(&four&),
5 =& println!(&five&),
_ =& println!(&something else&),
2、上例中的“ _ =& println!(&something else&),”表示上面都没匹配到的时候执行的方法,如果去掉会编译出错。Match要求所有的情况。
3、Match也是一个表达式,可以拿它的返回值。
fn cmp(a: int, b: int) -& Ordering {
if a & b { Less }
else if a & b { Greater }
else { Equal }
fn main() {
let x = 5i;
let y = 10i;
let result = match cmp(x, y) {
Less =& &less&,
Greater =& &greater&,
=& &equal&,
println!(&{}&, result); //will print 'less'
1、Rust不支持C那种传统的循环。Rust的for循环长这样。后面的expression是一个迭代器。
//In slightly more abstract terms,
//for var in expression {
for x in range(0i, 10i) {
println!(&{:d}&, x);
} // print 0 1 3 ... 9
2、While循环长这样。
let mut x = 5u;
let mut done =
while !done {
x += x - 3;
println!(&{}&, x);
if x % 5 == 0 { done = }
3、死循环有两种,有些微不同,推荐使用loop。
while true {
4、支持break跳出循环,continue进入下一次循环。
1、Rust有两种字符串。&str和String。前者类似Ruby中的Symbol,是静态不可变的。后者则放在堆上,动态可变。
2、这样就是&str。
let string = &Hello there.&;
3、&str用.to_string()转String。
let mut s = &Hello&.to_string();
4、String用.as_slice()转&str。
let s = &Hello&.to_string();
println!(s.as_slice());
5、&str和String之间必须用.to_string()或者.as_slice()转成相同类型后才可以做相等判断。
6、String-&&str便宜。&str-&String需要开内存,贵。Converting a String to a &str is cheap, but converting the &str to a String involves allocating memory. No reason to do that unless you have to!
1、Rust中的矢量类似其他语言中的Array。和Rust的字符串一样,有多种类型,共三种。
2、可变长矢量。叹号表示是宏而不是方法,宏后面可以用小括号活着中括号,是等价的。
let nums = vec![1i, 2i, 3i];
3、不可变长矢量。
let nums = [1i, 2i, 3i];
let nums = [1i, ..20]; // Shorthand for an array of 20 elements all initialized to 1
4、Slice矢量。
let vec = vec![1i, 2i, 3i];
let slice = vec.as_slice();
5、三种矢量都支持下标取值。
let names = [&Graydon&, &Brian&, &Niko&];
println!(&The second name is: {}&, names[1]);
6、三种矢量都支持.iter()迭代器。
let vec = vec![1i, 2i, 3i];
for i in vec.iter() {
println!(&{}&, i);
7、往矢量中添加元素的方法是.push(),不可变长矢量不可以.push()。
let mut nums = vec![1i, 2i, 3i];
nums.push(4i); // works
let mut nums = [1i, 2i, 3i];
nums.push(4i); //
error: type `[int, .. 3]` does not implement any method
// in scope named `push`
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致966,690 一月 独立访问用户
语言 & 开发
架构 & 设计
文化 & 方法
您目前处于:
枚举并发集合探讨
枚举并发集合探讨
日. 估计阅读时间:
不到一分钟
注意: 挥一挥衣袖,带走满满干货,关注,时不时发福利呦!
Author Contacted
相关厂商内容
相关赞助商
QCon北京-18日,北京&国家会议中心,
告诉我们您的想法
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
赞助商链接
架构 & 设计
文化 & 方法
<及所有内容,版权所有 &#169;
C4Media Inc.
服务器由 提供, 我们最信赖的ISP伙伴。
北京创新网媒广告有限公司
京ICP备号-7
注意:如果要修改您的邮箱,我们将会发送确认邮件到您原来的邮箱。
使用现有的公司名称
修改公司名称为:
公司性质:
使用现有的公司性质
修改公司性质为:
使用现有的公司规模
修改公司规模为:
使用现在的国家
使用现在的省份
Subscribe to our newsletter?
Subscribe to our industry email notices?
我们发现您在使用ad blocker。
我们理解您使用ad blocker的初衷,但为了保证InfoQ能够继续以免费方式为您服务,我们需要您的支持。InfoQ绝不会在未经您许可的情况下将您的数据提供给第三方。我们仅将其用于向读者发送相关广告内容。请您将InfoQ添加至白名单,感谢您的理解与支持。主题信息(必填)
主题描述(最多限制在50个字符)
申请人信息(必填)
申请信息已提交审核,请注意查收邮件,我们会尽快给您反馈。
如有疑问,请联系
傻丫头和高科技产物小心翼翼的初恋
如今的编程是一场程序员和上帝的竞赛,程序员要开发出更大更好、傻瓜都会用到软件。而上帝在努力创造出更大更傻的傻瓜。目前为止,上帝是赢的。个人网站:。个人QQ群:、
个人大数据技术博客:
在读大四学生一枚,学习过C++、java、C语言,windows编程、Linux编程,学过.....。目前主要学习C++、Qt编程。梦想做一位技术leader。乐于总结、乐于分享。目前从事Qt软件开发工作。}

我要回帖

更多关于 rust语言 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信