Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the address of a `struct` in Rust?

Tags:

struct

rust

I have tried using raw pointer casts, like my_struct as *const usize, but this results in a non-scalar cast error. Raw pointers seem to work fine when finding the address of primitives, but not custom structs.

like image 497
EpicPotato Avatar asked Mar 09 '16 04:03

EpicPotato


People also ask

How do you access structs in Rust?

How to access struct properties (members) We access struct properties with dot notation. That means we separate the struct's variable name and its property name with the dot operator. In the example above, we print the properties from each struct by accessing their values with dot notation.

How do you access the fields and their values for a given struct in Rust?

To get a specific value from a struct, we use dot notation. For example, to access this user's email address, we use user1. email . If the instance is mutable, we can change a value by using the dot notation and assigning into a particular field.

How do you print a pointer in Rust?

To print a raw pointer in Rust, call the println! or print! macro and use the syntax {:p} as part of the first string format argument. Finally, pass the variable you want to see the raw pointer as the second argument of the macro println! or print! .


1 Answers

You need to use the & operator to get the address of any variable, so you need to write &my_struct as *const _ (where _ can be a literal _, or the type of the value behind the pointer).

like image 124
Francis Gagné Avatar answered Nov 01 '22 17:11

Francis Gagné