unsafe super power - raw pointer in rust

Hi, this is my third blog for unsafe in rust, I feel that unsafe is a superpower in rust and I am interested in it, this blog is to have some brief intro to the unsafe.

The first time for me to use unsafe is in assignment1 (just for debug and code test): I want to have a global variable, and in rust, this needs unsafe:

Code here(just a sample, I have deleted the usage of unsafe in my assignment code so I can not provide a real code for it).

static mut COUNTER: i32 = 0;
fn increse_counter() {
    unsafe {
        COUNTER += 1;
    }
}

As you can see, if we want to mutate the COUNTER, I need to use the unsafe. The operation to the COUNTER should be wrapped by the unsafe block.

Another use of unsafe: raw pointer, is very representative. I will mainly talk about this.

The raw pointer is divided into: *mut T(mutable) and *const T(immutable).

What is the most important is : the raw pointer allow us to have mutable and immutable pointer to point at one position together! 

We can even have more than one mutable pointer to point to one position together!

But, when we are dereferencing these unsafe pointer, we need to wrap them with unsafe{}.

Code here:

Result:

 Amazing! We have a immutable and a mutable pointer pointing to the same number, and it works!

We can even change the value even with these pointer!

Do you feel that this is a taste of C? quite good!

And I can still remember in the earlier lecture for reference, we can not deal with the problem with simple reference:

       We want to split a vec:i32 into 2 part, and return 2 slice with borrow:

Error happened:

Actually, we just want to borrow from different part of the slice, The two parts do not intersect, but rust do not allow us to do it at all!

Previously, we can only try to take use of the provided function by rust to solve this problem, but now, we have unsafe and raw pointer, we can do it by ourselves!

Here we go!

Amazing! With the help of unsafe and raw pointer, it makes the previous impossible operation become possible! 

Those 2 samples below are the unsafe I have used before. I do think that the raw pointer makes me feel that I am using C! This is pretty cool!

But, what we need to know is that, it is not wise for us to use unsafe frequently, that is for the reason why it is called unsafe. 

Other possible usage of unsafe: take use of unsafe function. The unsafe function maybe like this: 

 There are unsafe keywords in the function signature.

I also want to know in which situation can we take use of the raw pointer safely, because I haven’t got enough experience for it, so, currently, I will still decide to use the safe operation provided by rust.

posted @ 2024-04-02 15:12  skywxp  阅读(58)  评论(0)    收藏  举报