What is the state of fn_traits?
⚓ Rust 📅 2025-11-13 👤 surdeus 👁️ 4Does anyone in the know, know what the state of the fn_traits feature is? Last I heard it was waiting on variadics, but I am wondering if anyone has insight into what the future might hold. The head of the tracked issue states "Cannot call implementations of the Fn* traits on references #42736" as one of the bugs being tracked. I attempted to fix this bug last February, but the project had bigger fish to fry. Subsequently, the bug was called a non-blocker for fn_traits.
fn_traits and unboxed_closures seem to be related, but neither has seen practically any movement as far as I can tell.
In the meantime I have played around with how to implement fn_traits in safe stable Rust, playground.
use derive_more::DerefMut;
use derive_more::Deref;
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Deref, DerefMut)]
struct Fib {
pub nums: Rc<RefCell<[i32; 2]>>,
#[deref]
#[deref_mut]
closure: Box<dyn FnMut(usize) -> i32>,
}
impl Fib {
pub fn new() -> Fib {
let nums = Rc::new(RefCell::new([0, 1]));
let closure_nums = Rc::clone(&nums);
let closure = Box::new(move |_i| {
let mut n = closure_nums.borrow_mut();
let [n0, n1] = &mut *n;
[*n0, *n1] = [*n1, *n0 + *n1];
*n0
});
Fib{nums, closure}
}
}
fn main() {
let mut fib_struct = Fib::new();
let fib_seq: [_; 10] = std::array::from_fn(&mut *fib_struct);
println!("{fib_seq:?}");
println!("next fib num: {:?}", fib_struct.nums.borrow()[1]);
}
The code above provides a fairly seamless experience for the user of the Fib struct, but the implementation isn't great. For one the closure is in a Box<dyn> when it really doesn't need to be. The closure can only be one type of closure, but since there is know way of specifying the type of the closure, it needs to be wrapped in the Box<dyn> or be a generic. The other issue is in how the state needs to be shared if the closure and struct want to have access to the data. If there was a way to reach into the closure to view and change the captured data, then the Rc<RefCell<T>> wouldn't needed.
The concise way we can express closures in Rust is great, but I feel like maybe we need a way to express more deliberate and complex closures. Closures that can have a specified type and data structure, and can implement their own functions. Maybe something like below? I only spent a few minutes thinking about this, so forgive me if this is a terrible idea. ¯\(ツ)/¯
struct Fib([i32; 2]) = |&mut self, _i: usize| -> i32 {
let [n0, n1] = &mut self.0;
[*n0, *n1] = [*n1, *n0 + *n1];
*n0
}
Thoughts?
1 post - 1 participant
🏷️ Rust_feed