Why "bring your own allocator" APIs are not more popular in Rust?

I think the main reason is that Rust picked the option of using a single global allocator early on in its existance and basically stuck with it. It can be easily seen, why they choose this approach given that no-std was yet to be invented and C++ (from which Rust has taken a lot of concepts) has a similar approach in its standard library.

Zig is a different example as "bring your own allocator and use it with standard containers" seems to be a core concept of the language (I think it might have even been invented there) and it has been taken into account in the entire design early on.

The reason why "bring your own allocator" is not used in Rust is because the standard libaries don't really support it. There is the Allocator trait alloc. But not only is it nightly only, but it also is limited by the fact, that it must fit into the preexisting structures. For example you cannot really use it to implement a failable allocator or for many kinds of area allocation, because of the way it is used e.g. in String and Vec. This makes it not that usefull. It is also questionable if custom allocators are the right abstractions, see Is custom allocators the right abstraction?.

My personal guess is that the proper solution would require a redesign of the api of the container types currently defined to alloc to overcome this limitations. This can be done in a backward compatible fashion. This might become more relevant due to the inclusion of Rust in the Linux kernel.

2 Likes