RUST学习

下文中的代码包含了大多数rust的基本语法和特性

main.rs

mod ext_mod;

#[derive(Debug)]
struct Person {
    name: String,
    age: i32,
    job: String
}

impl Person {
    fn info(&self) -> String {
        let info = format!("name: {}\nage: {}\njob: {}", self.name, self.age, self.job);
        info
    }
}


fn add(a:i32, b:i32) ->i32
{
    if a>b {
        return a;
    }
    else {
        return b;
    }
}

mod nation {
    pub mod government {
        pub fn govern() {
            super::congress::legislate();
        }
    }

    mod congress {
        pub fn legislate() {}
    }

    mod court {
        fn judicial() {
            super::congress::legislate();
        }
    }
}

mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String,
    }

    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seasonal_fruit: String::from("peaches"),
            }
        }
    }
}
pub fn eat_at_restaurant() {
    let mut meal = back_of_house::Breakfast::summer("Rye");
    meal.toast = String::from("Wheat");
    println!("I'd like {} toast please", meal.toast);
}

mod SomeModule {
    pub enum Person {
        King {
            name: String
        },
        Quene
    }
}


mod nation_wise {
    pub mod government {
        pub fn govern() {
            println!("keyword use demo");
        }
    }
    pub fn govern() {
        println!("this is nation govern");
    }
}

use crate::nation_wise::government::govern;
use crate::nation_wise::govern as nation_govern;

use std::fs::File;


fn max(array: &[i32]) -> i32 {
    let mut max_index = 0;
    let mut i = 1;
    while i < array.len() {
        if array[i] > array[max_index] {
            max_index = i;
        }
        i += 1;
    }
    array[max_index]
}

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}


trait Descriptive {
    fn describe(&self) -> String;
}

impl Descriptive for Person {
    fn describe(&self) -> String {
        format!("{} {}", self.name, self.age)
    }
}


trait Comparable {
    fn compare(&self, object: &Self) -> i8;
}

fn maximum<T: Comparable>(array: &[T]) -> &T {
    let mut max_index = 0;
    let mut i = 1;
    while i < array.len() {
        if array[i].compare(&array[max_index]) > 0 {
            max_index = i;
        }
        i += 1;
    }
    &array[max_index]
}

impl Comparable for f64 {
    fn compare(&self, object: &f64) -> i8 {
        if &self > &object { 1 }
        else if &self == &object { 0 }
        else { -1 }
    }
}



fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    if s2.len() > s1.len() {
        s2
    } else {
        s1
    }
}


use std::io::stdin;

use std::fs;

use std::io::prelude::*;

use std::collections::HashMap;

//类
mod second;
use second::ClassName;

//并发
use std::thread;
use std::time::Duration;

fn spawn_function() {
    for i in 0..5 {
        println!("spawned thread print {}", i);
        thread::sleep(Duration::from_millis(1));
    }
}


//消息传递
use std::sync::mpsc;




fn main() -> std::io::Result<()>
{
    let a=200;
    let b=300;
    let tup = (1, 2, 3);
    let c=add(a,b);
    println!("a is {0}, b is {1}", a, b);
    println!("{}", tup.0);
    println!("{}", c);
    for i in 1..5{
        println!("{}", i);
        if i == 4{
            break;
        }
    }
    let jack = Person{
        name: String::from("Jack"),
        age: 32,
        job: String::from("engineer")
    };
    // println!("His name is {}, he is {} years old, his job is {}", jack.name, jack.age, jack.job);
    println!("info: {}", jack.info());
    let t = "abc";
    match t {
        "abc" => println!("Yes"),
        _ => {},
    }

    nation::government::govern();

    eat_at_restaurant();

    let person = SomeModule::Person::King{
        name: String::from("Blue")
    };
    match person {
        SomeModule::Person::King {name} => {
            println!("{}", name);
        }
        _ => {}
    }


    println!("This is the main module.");
    println!("{}", ext_mod::message());

    // panic!("error occured");

    govern();
    nation_govern();


    let f = File::open("hello.txt");
    match f {
        Ok(file) => {
            println!("File opened successfully.");
        },
        Err(err) => {
            println!("Failed to open the file.");
        }
    }


    let a = [2, 4, 6, 3, 1];
    println!("max = {}", max(&a));

    let p = Point { x: 1, y: 2 };
    println!("p.x = {}", p.x());

    println!("{}", jack.describe());


    let arr = [1.0, 3.0, 5.0, 4.0, 2.0];
    println!("maximum of arr is {}", maximum(&arr));


    //生命周期
    let r;
    {
        let s1 = "rust";
        let s2 = "ecmascript";
        r = longer(s1, s2);
    }
    println!("{} is longer", r);


    let args = std::env::args();
    for arg in args {
        println!("{}", arg);
    }


    //命令行输入
    // let mut str_buf = String::new();
    // stdin().read_line(&mut str_buf)
    //     .expect("Failed to read line.");

    // println!("Your input line is \n{}", str_buf);

    //文本文件读取
    let text = fs::read_to_string("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt").unwrap();
    println!("{}", text);
    let content = fs::read("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt").unwrap();
    println!("{:?}", content);
    //文件流读取
    let mut buffer = [0u8; 5];
    let mut file = fs::File::open("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt").unwrap();
    file.read(&mut buffer).unwrap();
    println!("{:?}", buffer);
    file.read(&mut buffer).unwrap();
    println!("{:?}", buffer);


    //vector向量
    let mut vector = vec![1, 2, 4, 8];
    vector.push(16);
    vector.push(32);
    vector.push(64);
    println!("{:?}", vector);
    //一个向量拼接到另一个向量尾部
    let mut v1: Vec<i32> = vec![1, 2, 4, 8];
    let mut v2: Vec<i32> = vec![16, 32, 64];
    v1.append(&mut v2);
    println!("{:?}", v1);
    //从向量中取值
    let mut v = vec![1, 2, 4, 8];
    println!("{}", match v.get(0) {
        Some(value) => value.to_string(),
        None => "None".to_string()
    });
    //遍历向量
    let v = vec![100, 32, 57];
    for i in &v {
            println!("{}", i);
    }
    //遍历过程中改变向量
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }

    //基础类型转字符串
    let one = 1.to_string();         // 整数到字符串
    let float = 1.3.to_string();     // 浮点数到字符串
    let slice = "slice".to_string(); // 字符串切片到字符串
    //包含utf8的字符串
    let hello = String::from("السلام عليكم");
    let hello = String::from("Dobrý den");
    let hello = String::from("Hello");
    let hello = String::from("שָׁלוֹם");
    let hello = String::from("नमस्ते");
    let hello = String::from("こんにちは");
    let hello = String::from("안녕하세요");
    let hello = String::from("你好");
    let hello = String::from("Olá");
    let hello = String::from("Здравствуйте");
    let hello = String::from("Hola");
    //字符串追加
    let mut s = String::from("run");
    s.push_str("oob"); // 追加字符串切片
    s.push('!');       // 追加字符
    //+号拼接字符串
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");
    let s = s1 + "-" + &s2 + "-" + &s3;
    //使用format宏
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = format!("{}-{}-{}", s1, s2, s3);
    //字符产长度
    let s = "hello";
    let len = s.len();
    println!("{}", len);
    let s = "你好";
    let len = s.len();
    println!("{}", len);
    let s = "hello你好";
    let len = s.chars().count();
    println!("{}", len);
    //遍历字符串
    let s = String::from("hello中文");
    for c in s.chars() {
        println!("{}", c);
    }
    //从字符串中取单个字符
    let s = String::from("EN中文");
    let a = s.chars().nth(2);
    println!("{:?}", a);
    //截取字符串
    let s = String::from("EN中文");
    let sub = &s[0..2];
    println!("{}", sub);

    //映射表
    let mut map = HashMap::new();

    map.insert("color", "red");
    map.insert("size", "10 m^2");

    println!("{}", map.get("color").unwrap());
    //映射表迭代器
    let mut map = HashMap::new();

    map.insert("color", "red");
    map.insert("size", "10 m^2");

    for p in map.iter() {
        println!("{:?}", p);
    }
    //改变键值
    let mut map = HashMap::new();
    map.insert(1, "a");

    if let Some(x) = map.get_mut(&1) {
        *x = "b";
    }


    //类
    let object = ClassName::new(1024);
    object.public_method();

    //线程
    // thread::spawn(spawn_function);

    // for i in 0..3 {
    //     println!("main thread print {}", i);
    //     thread::sleep(Duration::from_millis(1));
    // }

    //线程闭包
    thread::spawn(|| {
        for i in 0..5 {
            println!("spawned thread print {}", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 0..3 {
        println!("main thread print {}", i);
        thread::sleep(Duration::from_millis(1));
    }

    //闭包
    let inc = |num| {
        num + 1
    };
    println!("inc(5) = {}", inc(5));

    //join方法
    let handle = thread::spawn(|| {
        for i in 0..5 {
            println!("spawned thread print {}", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 0..3 {
        println!("main thread print {}", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();

    //强制迁移所有权
    let s = "hello";

    let handle = thread::spawn(move || {
        println!("{}", s);
    });

    handle.join().unwrap();

    //消息传递
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);






    //文件写入
    fs::write("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt", "FROM RUST PROGRAM")
        .unwrap();
    //另一种写入方法
    let mut file = File::create("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt").unwrap();
    file.write(b"Hello, Rust!").unwrap();
    //添加文件内容
    let mut file = fs::OpenOptions::new()
            .append(true).open("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt")?;

    file.write(b" APPEND WORD")?;

    //读写权限打开,覆盖内容方式
    let mut file = fs::OpenOptions::new()
            .read(true).write(true).open("D:\\WorkSpace\\RUST\\learn\\target\\debug\\test.txt")?;

    file.write(b"COVER")?;

    Ok(())

}


ext_mod.rs

pub fn message() -> String {
    String::from("This is the 2nd module.")
}

second.rs

pub struct ClassName {
    field: i32,
}

impl ClassName {
    pub fn new(value: i32) -> ClassName {
        ClassName {
            field: value
        }
    }

    pub fn public_method(&self) {
        println!("from public method");
        self.private_method();
    }

    fn private_method(&self) {
        println!("from private method");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值