I started porting C code to Rust, but I'm confused about how things work in Rust. What is the equivalent of this code:
typedef struct Room {
int xPos;
int yPos;
} Room;
void main (){
Room **rooms;
rooms = malloc(sizeof(Room)*8);
}
I started porting C code to Rust, but I'm confused about how things work in Rust. What is the equivalent of this code:
typedef struct Room {
int xPos;
int yPos;
} Room;
void main (){
Room **rooms;
rooms = malloc(sizeof(Room)*8);
}
Assuming you mean "a collection of
Room
s with capacity for 8":It's exceedingly rare to call the allocator directly in Rust. Generally, you have a collection that does that for you. You also don't usually explicitly specify the item type of the collection because it can be inferred by what you put in it, but since your code doesn't use
rooms
at all, we have to inform the compiler.As pointed out in the comments, you don't need a double pointer. This is the equivalent of a
Room *
. If you really wanted an additional level of indirection, you could addBox
:One of the benefits of Rust vs C is that in C, you don't know the semantics of a
foo_t **
. Who should free each of the pointers? Which pointers are mutable? You can create raw pointers in Rust, but even that requires specifying mutability. This is almost never what you want:In certain FFI cases, a C function accepts a
foo_t **
because it wants to modify a passed-in pointer. In those cases, something like this is reasonable: