Why isn't Rust able to infer the type here?
I have a struct Widgetfor which I have a constructor Widget::stateless(...). It simply sets the state to be (). However, even though IDE autocomplete can see that the generic parameter State = (), Rust is unable to infer the type of State:
// widget.rs
impl<State> Widget<State>
where
State: 'static + PartialEq,
{
pub fn stateless(
builder: impl Fn() -> Rc<RefCell<dyn Component>> + 'static,
) -> Rc<RefCell<dyn Component>> {
Rc::new(RefCell::new(Widget {
state: (),
prev: None,
needs_rebuild: true,
builder: Box::new(move |_| builder()),
on_keypress: Box::new(|_, _| ()),
create_element: Rc::new(|this| this._build().borrow_mut().create_element()),
}))
}
// ...
}
// number.rs
pub fn number(i: i32) -> Rc<RefCell<dyn Component>> {
Widget::stateless(move || text(i.to_string()))
}
The above code yields the following error:
error[E0283]: type annotations needed
--> react/src/widgets/number.rs:7:5
|
7 | Widget::stateless(|| text(i.to_string()))
| ^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `State` declared on the struct `Widget`
|
= note: cannot satisfy `_: PartialEq`
Apparently I have to do this instead:
pub fn number(i: i32) -> Rc<RefCell<dyn Component>> {
Widget::<()>::stateless(move || text(i.to_string()))
}
which works but isn't as pretty. Why can't Rust infer that State is () despite it being very clear in Widget::stateless? Is there anything I can do to avoid writing out ::<()> at the call site? Thanks
Posted Nov 1, 2025, 1:15 PM UTC
04