结构体

带名字的结构体

struct s{
	a: i32,
	b:i32
}

不带参数名字的结构体(元组结构体)

struct Color(i32, i32, i32); 

不带括号的结构体

struct Test;

使用impl为结构体定义方法

impl Test{
	fn method1(&self:&Self){
		println!("hello");
	}
	fn method2(a:i32){
		println!("{a}");
	}
}
let test:Test = Test;
test.method1();//方法调用 (定义时加self)是一个语法糖相当于 Test::method1(&test);
Test::method2(6);//内联函数调用(定义时不用加self)

枚举

enum Color{
	Red,
	Blue,
	Green
}

特殊的enumOption<T>,被包含在preclude里,不用导入就可以使用,用于表示类似其它语言的空值,引入这个特性是为了防止别的语言里对空值进行操作,使用Option就必须处理这种情况

enum Option<T>{
	None,
	Some(T)
}

使用match 匹配

enum Country{
	China,
	Us
}
enum Money{
	one,
	five,
	ten,
	hundred(Country)
}

使用match匹配默认要处理所有情况,注意:使用的是=>而不是->
使用if let 匹配只要处理一种情况

项目结构

错误处理

有一个Result<T>枚举,也是在preclude里的

enum Result<T,E>{
	Ok(T),
	Err(E),
}

如果对一个Option或者Result类型调用.unwrap()方法,当值为None or Err时就会panic

let file = File::open("").unwrap();

如果要在panic时显示自定义信息,那就使用.expect("error msg"),主义这是expect而不是except,表示panic时期望的输出

let file = File::open("").expect("open failed");

如果不让程序panic,要进行错误处理

fn open_file(path:&str) -> result:Result<(),std::io:Error>
	let file = match File::open(path){
		Ok(f) => f,
		Err() => {
			println!("open faild,please check you path")
		}
	}
	Ok(())
}

有一种简便的方式等价于这种错误处理

fn open_file(path:&str) -> result:Result<(),std::io:Error>
	let file = File::open(path)?
	Ok(())
}

生命周期

省略规则

fn test(x:&str) ->&str{}//参数中只有一个应用,默认使用它的生命周期

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {//有&self 输出参数没有引用,不需要生命周期
        3
    }
}

impl<'a> ImportantExcerpt<'a> {
    fn announce_and_return_part(&self, announcement: &str) -> &str {
    //有&self ,&str默认生命周期为&self的生命周期
        println!("Attention please: {announcement}");
        self.part
    }
}