Dyn FnOnce without allocating

⚓ Rust    📅 2025-08-06    👤 surdeus    👁️ 4      

surdeus

How can I go from impl FnOnce to dyn FnOnce in a way that allows me to call the function without moving it to the heap? I am trying to write code with generic callbacks that need to be FnOnce for API ergonomics, but I don’t want a copy of the implementation for every callback, so I want to use dyn, but I don’t want to have to make an unnecessary heap allocation every time this function is called just to be able to call the dyn FnOnce.

One solution I thought about is impl FnMut for Option<impl FnOnce> (through a wrapper struct) which would take the function out and panic on None but 1 I can’t implement it in stable Rust and 2 it can’t be unsized due to the Option.

I am mostly annoyed because I don’t intuitively recognise any reason why this shouldn’t be possible but there is some strange combination of language limitations that is not alowying this to work.

12 posts - 6 participants

Read full topic

🏷️ Rust_feed