Is there something like placement new?


Say I allocate a piece of raw memory in C, and I want to initialize a struct on this piece of raw memory in rust, I will need such kind of things like placement new.

And there may be some other conditions when implementing a memory pool.


You can use ptr::write or one of its variants to put Rust structs at a particular memory address.


ptr::write makes sense if C has to do the allocation, but if you can avoid it, that’s probably even better; It’s always more complicated if memory allocation and memory usage happen on different sides of the FFI border.

It is quite common to have Rust allocate the Rust objects, and then using box::into_raw to get the raw pointer out to the C-side. (and box::from_raw to get it back into Rust)

I’m not sure how applicable this is, since you mention “memory pools”…


Rust had experimental placement-new syntax, but removed it a few months ago. You can see a summary of that decision here:


Note also you may need to use drop_in_place.
If not or reallocating unsafe { *ptr = val; } works.