跳到主内容
Rust
文章阅读

rust 1.88 新特性,if let 链,裸指针,cfg新判断

2025/12/16163 次阅读2 分钟

编译要加–edition 2024 不然会报错


rustc --edition 2024 new_future.rs


use std::cell::Cell;

enum UserStatus {
    Active(u32,String),
    Inactive,
    Pending
}

fn get_current_user_status() -> UserStatus {
    UserStatus::Active(922111,"梁典典".to_string())
}


// cfg - 总会被调用
#[cfg(true)]
fn feature_always_on(){
    println!("这个函数总是会被调用");
}

// cfg - 永远不编译
#[cfg(false)]
fn feature_never_compiled(){
     println!("这个函数永远不会被编译");
}


// cfg - 仅在特定条件下编译
#[cfg(all(target_os = "linux",true))] // true 结合其他条件
fn linux_specific_function(){
    println!("这个函数仅在特定条件下编译");
}




// 1.88 新特性
fn main(){

    feature_always_on();
    #[cfg(target_os = "linux")]
    linux_specific_function();

    if let UserStatus::Active(id,name) = get_current_user_status() && id>100000 && id < 199999 && name.len() > 5{
        println!("{}",name);
    }else{
        println!("不符合要求");
    }


    //cell update
    let count = Cell::new(0);
    count.update(|x| x + 1);
    println!("count: {}", count.get());


    let default_const_ptr: *const u32 =  Default::default();
    let default_mut_ptr: *mut String = Default::default();

    println!("default_const_ptr: {:?}, default_mut_ptr: {:?}", default_const_ptr, default_mut_ptr);
}

输出


$ ./new_future
这个函数总是会被调用
不符合要求
count: 1
default_const_ptr: 0x0, default_mut_ptr: 0x0
返回顶部