How can I use a structure reference for isize?

I want to get bin the following code.

unsafe {
    struct Test {
        num: i32,
    }
    let a = Test { num: 0 };
    let b = &mut a as isize;
}

But this leads to the following error message.

error: casting `&on_create::Test` as `isize` is invalid
   --> main.rs:181:15
    |
181 |       let b = &a as isize;
    |    

I thought he would be forced to *const _, and then apply ptr-addr-cast . What did I miss? Should i use mem::transmute?

+4
source share
2 answers

I thought he would be forced to *const _, and then ptr-addr-cast is applied ....

Firstly, implicit coercion does not occur everywhere and, of course, not inside a part of an expression of the type e as T, as you have noticed. The places where coercion occurs are called coercion sites , usually you do an expression assessment, for example.

  • RHS let/const/static:

    let x = foo
    //      ^~~
    
  • :

    foo(bar)
    //  ^~~
    
  • :

    fn f() -> u32 {
        foo
    //  ^~~
    }
    
  • struct/array/tuple:

       [foo, bar, baz]
    //  ^~~  ^~~  ^~~
       (foo, bar, baz)
    //  ^~~  ^~~  ^~~
       Foo { field: foo }
    //              ^~~
    
  • :

    { ...; foo }
    //     ^~~
    

foo as isize .

-, , , Rust , . &mut Test &Test *mut Test *const Test &mut SomeTrait .., ! , , :

#![feature(type_ascription)]

let b = {&a}: *const _ as isize;
//       ^~ ^~~~~~~~~~
//        |   we explicitly make the type a const raw pointer
//        |                             using type-ascription
//        a coercion site

, &a as *const _ as isize.

+5

; "" / (-?):

struct Test {
    num: i32,
}
let a = Test { num: 0 };
let b = &a as *const _ as isize;

, . , unsafe .

+4

Source: https://habr.com/ru/post/1674855/


All Articles