• 一、枚举

    1. 枚举数据类型的存储结构是一个联合体。
    2. 它的每个变体(子项)都是枚举类型的的构造方法。枚举的构造方法只有参数类型没有形参。如:
      enum MyEnum<T> {A(T),/*不是 A(x:T)*/}   
    3. 无参数变体可以直接作为枚举类型的一个实例。
    4. 枚举的有参数构造构造函数传入实参后生成枚举类型的一个实例。
    5. Option<T> 是枚举类型,Some(T) 和 None 是它的两个实例;Result<T,E> 是枚举类型,Ok(T) 和 Err(E) 是它的两个实例。
    6. 枚举的变体构造函数可以包含多个参数以达到存储不同类型数据的目的。
      1. 比如:用枚举实现的头+数据广义表。
        #![allow(unused, warnings)]
        
        use std::boxed::Box;
        
        #[derive(Debug)]
        enum List<i32> {
            Nil,
            Cons(i32, Box<List<i32>>),
        }
        
        impl List<i32> {
            fn head(&self) -> &i32 {
                match self {
                    List::Cons(x, _) => x,
                    List::Nil => &1,
                }
            }
        
            fn tail(&self) -> &List<i32> {
                match self {
                    List::Cons(_, x) => &*x,
                    List::Nil => &List::Nil,
                }
            }
        }
        
        fn into_vec(x: List<i32>, mut r: Vec<i32>) -> Vec<i32> {
            return match x {
                List::Nil => r,
        
                List::Cons(x, y) => into_vec(*y, {
                    r.push(x);
                    r
                }),
            };
        }
        
        fn fib(a: List<i32>, n: i32) -> List<i32> {
            if n == 0 {
                return a;
            }
        
            return match a {
                List::Nil => fib(
                    List::Cons(1, Box::new(List::Cons(1, Box::new(List::Nil)))),
                    n - 1,
                ),
                List::Cons(_, _) => fib(List::Cons(*a.head() + *a.tail().head(), Box::new(a)), n - 1),
            };
        }
        
        fn main() {
            let v = List::Cons(1, Box::new(List::Cons(1, Box::new(List::Nil))));
        
            println!("{:?}", into_vec(fib(v, 20), Vec::<i32>::new()));
        }
        
  • 二、Rc

    1. let x = Rc::new(1); x 不可用 Rc(y) = x 匹配解构, 可以直接解引用 *x 得到 1
  • 三、编译选项

[profile.release]
opt-level = "z"     # 优化目标改为体积("z"比"s"更激进) 
lto = true          # 开启链接时优化,跨模块移除死代码 
codegen-units = 1   # 减少并行单元,换取更极致的全局优化 
panic = "abort"     # Panic时直接终止,不生成栈展开信息 
strip = true        # 剥离符号表,发布必需

  

posted on 2026-10-02 11:48  Freud  阅读(4)  评论(0)    收藏  举报