Rust引用借用 vs 原始指针

rust 复制代码
let v: i32 = 10;
let v1 = &v;
let a: *const i32 = &v;
println!("a={:p}", a);
let b = a as *mut i32;  //无法从&v直接转换成*mut i32,需要从*const i32过度
println!("b={:p}", b);
unsafe {
    *b+=1;
}
println!("v={}   v1={}", v, v1);

输出

复制代码
a=0xa7c8fb4d8
b=0xa7c8fb4d8
v=11   v1=11
rust 复制代码
    let mut mv: i32 = 10;
    let mut mv2 = &mut mv;
    *mv2 = *mv2 + 1;
    let p1 = mv2 as *const i32 as *mut i32;
    unsafe {
        *p1 += 1;
    }
    //let p2 = mv2 as *const i32;
    let mv3 = unsafe {
        let i: i32 = *p1;
        i
    };
    println!("mv2={}  mv3={}", mv2, mv3);

mv2=12 mv3=12

rust 复制代码
    use std::borrow::Cow;
    use std::os::raw::c_char;
    use std::ffi::CStr;
    let C: [u8; 11] = [116, 104, 97, 110, 107, 115, 102, 105, 115, 104, 0];
    let c_str: Cow<str>;
    unsafe{
        let c_ptr = &C as *const u8 as *const c_char;
        c_str = CStr::from_ptr(c_ptr).to_string_lossy();
    }
    println!("c_str is    {}", c_str);

c_str is thanksfish

原始指针和unsafe块配合,可以避过引用借用保护,但也失去了rust的优势。rust严谨也足够灵活...,除非必要原始指针慎用,用多了又变成c了...

相关推荐
SomeOtherTime16 小时前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
SomeOtherTime21 小时前
番外篇(第 12 讲):走向工业界深水区——从物理定律看 Rust 在真实工程中的“降维打击”与“阿喀琉斯之踵”
开发语言·rust
Kapaseker1 天前
Rust 桌面开发到底怎么选?先看这篇文章!
rust
奶油话梅糖1 天前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
wflynn1 天前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime2 天前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust
SomeOtherTime2 天前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust
wflynn3 天前
GitHub 今日推荐|Stela:在 PC 上直接启动 macOS 的翻译层
rust·开源·github
aifannihao3 天前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
鶴哥只手遮天3 天前
《rustc 内幕》第 1 章 全景:rustc 编译流水线与 crate 版图
后端·rust·开源