结构体
struct Point {
    x: f64,
    y: f64
}
let mut mypoint = Point { x: 1.0, y: 1.0 };
let origin = Point { x: 0.0, y: 0.0 };

mypoint.y += 1.0; // `mypoint` is mutable, and its fields as well
origin.y += 1.0; // ERROR: assigning to immutable field
match mypoint {
    Point { x: 0.0, y: yy } => println!("{}", yy),
    Point { x: xx,  y: yy } => println!("{} {}", xx, yy)
}

match mypoint {
    Point { x, .. } => println!("{}", x)
}
如果结构体变量是可变的,那么结构体里边的变量也是可变的。,..表示你忽略别的所有其他struct成员变量。 枚举
enum Direction {
    North,
    East,
    South,
    West
}
enum Color {
  Red = 0xff0000,
  Green = 0x00ff00,
  Blue = 0x0000ff
}
enum Shape {
    Circle(Point, f64),
    Rectangle(Point, Point)
}
use std::f64;
fn area(sh: Shape) -> f64 {
    match sh {
        Circle(_, size) => f64::consts::PI * size * size,
        Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y)
    }
}
第一个元素没有定义值,默认为0,依次加1。当为整数型,可用ad操作符转换成整数。进行匹配的时候,下划线代表忽略一个,”..“表示忽略所有。 元组
let mytup: (int, int, f64) = (10, 20, 30.0);
match mytup {
  (a, b, c) => println!("{}", a + b + (c as int))
}
元组结构体
struct MyTup(int, int, f64);
let mytup: MyTup = MyTup(10, 20, 30.0);
match mytup {
  MyTup(a, b, c) => println!("{}", a + b + (c as int))
}
相比元组,元组结构体有名字,所以Foo(1,2)和Bar(1,2)是不同的类型值。 只有一个元素的结构体元组是”newtype“,新名字是一个新类型,而不是一个已存在类型的别名。 碉堡的用法:
let length_with_unit = Inches(10);
let Inches(integer_length) = length_with_unit;
println!("length is {} inches", integer_length);
看完第五节,我已经想大体看完写点程序了。前边大部分也能看看程序就大体知道啥意思,不过还是把英文说的小细节看了一下。看到这里我觉得rust比golang更好,说不上来是不是细节的用法,他们有很多相似,但是感觉rust更顺眼一些。看的过程中我都怀疑是不是一帮人搞的两个差不多的东西。。

上一篇:
下一篇:

相关文章:

Categories: 博客记录

0 Responses so far.

Leave a Reply