rust语言基础学习: 使用ref关键字在模式匹配中通过引用进行绑定
今天来学习rust中的ref关键字。
由一个例子引出ref关键字的使用 先看下面的例子。
例1:
#[derive(Debug)] enum HttpMethod { Get(Get), Post(Post), } #[derive(Debug)] struct Get { url: String, } #[derive(Debug)] struct Post { url: String, body: Vec<u8>, } fn main() { let method = HttpMethod::Get(Get{ url: String::from("https://google.com"), }); match method { HttpMethod::Get(get) => println!("send get reuqest: {:?}", get), HttpMethod::Post(post) => println!("send post reuqest: {:?}", post), } println!("{:?}", method); // 编译错误: borrow of partially moved value: `method` } 上面例1中在使用match表达式进行模式匹配时,在执行第25行或26行时method会发生部分移动(partially moved),根据rust所有权规则中的Move语义,method将失去所有权,因此在第29行无法再使用method变量,报了编译错误。