Variable declaration in Rust language, Tuples (tuples), arrays (Arrays), slices (Slices), enum (enumeration), struct (structure)

statement

insert image description here

method

insert image description here

Basic Data Types Tuples, Arrays and Slices

A tuple is a collection of values ​​of different types. Tuples are constructed using parentheses ()

insert image description here

Arrays

An array is a collection of objects of the same type T stored in contiguous memory. Arrays are created using square brackets [] whose length is known at compile time in the format: [T; length].
insert image description here

Slices

Slices are similar to arrays, but their length is not known at compile time. Instead, a slice is a two-word object; the first word is a pointer to the data, and the second word is the length of the slice. The word size is the same as usize and is determined by the processor architecture, e.g. 64 bits on x86-64.

fn main() {
    
    
    //切片相关内容 
    //切片格式:[开始索引..结束索引],长度可变
    //声明一个空数组
    let empty: [String;0] = [];
    println!("empty={:?}", empty);
    
    let init: [i32;8] = [1,2,3,4,5,6,7,8];
    //定义一个切片
    let  a= &init[0..5];
    println!("取五个数后的值:{:?}",a);

    //声明一个字符串
    let mut s = String::from("Hello world");
    
    let wordIndex = first_world(&s);
    //s.clear();//会报错,因为不可变量的引用是不能随意更改的,如果修改,下面的
    //wordIndex就没有意义了
    println!("{}",wordIndex);

    /**
     * 计算第一个单词,以空格区分
     */
    fn first_world(s: &String) -> &str {
    
    

    let bytes = s.as_bytes( );
    for (i, &item) in bytes.iter().enumerate( ) {
    
    
        if item == b' ' {
    
    
            //如果是空格,返回从初始位置到第i的位置
            return &s[..i];
        }  
    }
    //返回所有的元素
     return &s[..];
    }
}

custom data type

structure

#[derive(Debug)]
//定义一个结构体
struct Rectangle {
    
    
    width: u32,
    height: u32,
}

//定义一个空结构体
struct Uint;

// 定义一个元组类型的结构体
struct Pair(i32, f32);


//实现该结构体,可以在这里面写方法,例如:初始化,返回某些值等其他函数
impl Rectangle {
    
    
    
    //算面积,返回u32
    fn area(&self) -> u32{
    
    
        self.width * self.height
    }
}


fn main() {
    
    
    //输出一个Pair结构体
    let pair = Pair(1, 0.1);
    println!("pair的值为:{:?}", pair.0);
    //初始化一个Rectangle
    let  tangle = Rectangle {
    
    
         width: 20,
        height: 10,
     };
    println!("tangle的值为:{:?}", tangle);
    //直接这个结构体吊该方法即可
    println!("面积是:{:?}", tangle.area())


}

Output result:
insert image description here

enumerate

The enum keyword allows to create a type which can be one of a number of different variants. Any variant that is valid in a struct is also valid in an enum.

#[derive(Debug)]
//定义一个简单的枚举
enum IpAddrKind {
    
    
    V4,
    V6,
}
//枚举带类型的
enum Ip {
    
    
    V4(String),
    V6(String),
}

//嵌套枚举
struct IpAddr {
    
    
    kind: IpAddrKind,
    address: String,
}

impl Ip {
    
    
    fn call(&self) {
    
    
        //打印值
        println!("{}", "HAHAHH");
    }
}
//
enum Book {
    
    
        Papery {
    
    index: u32},
        Electronic {
    
    url: String},
    }


fn main() {
    
    
    let home = IpAddr {
    
    
        kind: IpAddrKind::V4,
        address: String::from("127.0.0.1"),
    };
    println!("{:?}", home.kind);

    let loopback = IpAddr {
    
    
        kind: IpAddrKind::V6,
        address: String::from("::1"),
    };

    println!("{:?}", loopback.address);

    let plus = Ip::V4(String::from("value"));
    let pl = Ip::V6((String::from("value")));
    println!("{:?}", plus.call());



    let book = Book::Papery{
    
    index: 1001};
    let ebook = Book::Electronic{
    
    url: String::from("url...")};
    //打印bool值
    match book {
    
    
        Book::Papery {
    
     index } => {
    
    
            println!("Papery book {}", index);
        },
        Book::Electronic {
    
     url } => {
    
    
            println!("E-book {}", url);
        }
    }
    //match用来匹配数据
    let t = "abc";
     match t {
    
    
        "ab" => println!("Yes"),
        //太多了,没办法表示了,用下划线,剩下的都走这个
        _ => println!("No"),
    }
}

Print result:
insert image description here

Guess you like

Origin blog.csdn.net/ydl1128/article/details/130095215