rust进阶-基础.2.Option类型
Option类型是Rust中非常重要的一个类型,和Result也类似。本文主要根据文档:枚举类型Option编写
主要阐述以下内容:
1.Option和Result比较
2.Option的主要方法
3.示例
1.Option和Result比较
以下内容来自于文心一言
特性OptionResult目的表示一个值可能存在(Some(T))或不存在(None),避免空指针异常。表示一个操作可能成功(Ok(T))或失败(Err(E)),需携带错误信息。典型场景集合查找(如Vec::get)、可选字段(如链表节点的next指针)。文件I/O、网络请求、解析验证(如JSON反序列化)。错误处理仅表示值的存在性,无法传递错误上下文(如None无法区分“未找到”与“空输入”)。通过Err(E)携带错误类型,支持精细化错误处理(如区分“文件不存在”与“权限不足”)。这些应该是主要的差异。
Result可以传递错误信息。
2.Option的主要方法
3.示例
use std::iter::Sum;#struct Area { width: u32, height: u32, flag: bool,}impl Default for Area { fn default() -> Self { Area { width: 103, height: 2012, flag: true, } }}impl Iterator for Area { type Item = u32; fn next(&mut self) -> Option { if self.flag { let area = self.width * self.height; self.flag = false; Some(area) } else { None } }}/** * 实现这个以便直接比较两个Area对象的大小,因为Rust不允许直接对结构体进行比较 */impl PartialEq for Area { fn eq(&self, other: &Self) -> bool { let self_area = self.width * self.height; let other_area = other.width * other.height; self_area == other_area }}/** * 实现这个以便直接比较两个Area对象的大小,因为Rust不允许直接对结构体进行比较 */impl PartialOrd for Area { fn partial_cmp(&self, other: &Self) -> Option { let self_area = self.width * self.height; let other_area = other.width * other.height; Some(self_area.cmp(&other_area)) }}impl Area { fn area(&self) -> u32 { self.width * self.height }}#struct Exam{ test_time:u32, score:u32,}impl Sum for Exam{ fn sum<I>(iter: I) -> Self where I: Iterator{ let mut total=Exam{test_time:0,score:0}; for x in iter{ if total.test_time==0 { total.test_time = x.test_time; } total.score += x.score; } total}}fn main() { println!("\n-- 测试直接操作 \n"); let _r = test_direct_add(Some(1), Some(2)); //两个同种Option直接比较 println!("\n-- 测试直接比较 \n"); test_direct_compare(); // println!("\n-- 测试抽取值相关的方法 \n"); test_extract_value(); println!("\n-- 测试修改相关的方法 \n"); test_modify(); println!("\n-- 测试操作相关的方法 \n"); test_operate(); println!("\n-- 测试查询 \n"); let value = Some(String::from("健康饮食。66天养成一个习惯")); test_query(value); println!("\n-- 测试引用相关的方法 \n"); test_ref(); println!("\n-- 测试转换相关的方法 \n"); test_transform(); }/** * 两个Option可以直接比较,如果二者都实现了PartialOrd(Ord也可以) * 那么可以使用基本的比较运算符进行比较 */fntest_direct_compare(){ println!("要求其中的T实现PartialOrd"); let d=Area::default(); let a=Area{width: 10, height:20, flag:true}; if d>a{ println!("{:?}>{:?}",d,a); }else{ println!("{:?}
页:
[1]