[][src]Function tao_of_rust::ch13::unsafe_intro::unsafe_intro

pub fn unsafe_intro()

Unsafe Rust介绍

Basic usage: Unsafe中依旧会进行借用检查

error[E0502]: cannot borrow a as mutable because it is also borrowed as immutable

fn main(){
    unsafe {
        let mut a = "hello";
        let b = &a;
        let c = &mut a;
    }
}Run

Basic usage: Unsafe块示意

fn main() {
    let hello = vec![104, 101, 108, 108, 111];
    let hello = unsafe {
        // 该函数为unsafe函数
        String::from_utf8_unchecked(hello)
    };
    assert_eq!("hello", hello);
}Run

Basic usage: 访问和修改可变静态变量

static mut COUNTER: u32 = 0;
fn main() {
    let inc = 3;
    unsafe {
        COUNTER += inc;
        println!("COUNTER: {}", COUNTER);
    }
}Run