How to refer to a variable used in an insecure block?

I am trying to read 4 bytes from a socket and then convert these bytes to one u32.

let mut length: u32 = 0;

// Transmute 4 byte array into u32
unsafe {
    let length = mem::transmute::<[u8; 4], u32>(buf); // buf is the 4 item array of u8 that the socket was read into
    println!("1: {:}", length);
}

println!("Length: {:}", length);

However, the length is initially 0 once outside the insecure block. How can I get around this?

+4
source share
2 answers

In the inner block, you do not assign a new value to the external binding length, you obscure it by defining a new binding length.

I believe that in a simple piece of code such as this (where the external mutable variable is not reassigned), there should usually be a compiler warning line by line:

warning: the variable must not be changed

, , , , , - let unsafe.

, :

  • , .
  • ( , ), . Mutability .

:

let length: u32; // or mut  
unsafe {
    length = mem::transmute::<[u8; 4], u32>(buf);
    println!("1: {:}", length);
}

println!("Length: {:}", length);
+7

( ), , :

let buf = [1u8, 2, 3, 4];

// Transmute 4 byte array into u32
let length = unsafe {
    let length = std::mem::transmute::<[u8; 4], u32>(buf); // buf is the 4 item array of u8 that the socket was read into
    println!("1: {:}", length);
    length
};

println!("Length: {:}", length);

:

let length = unsafe {std::mem::transmute::<[u8; 4], u32>(buf)};
+4

All Articles