Closed audunhalland closed 2 years ago
I tested this and it basically works, but it requires adding a Copy
bound for dependencies:
#[entrait(Foo)]
fn foo(deps: &(impl Bar + Copy)) {
deps.bar();
}
So I don't think this will be worth it.
But of course, the generated traits can be modified to have Copy
as a supertrait 😎
If that is done, I think it will work.
Another consequence of this will be that it will be impossible to consume dependencies. But I can't really see any use cases for that, so should be fine.
Yet another consequence (which appears to be a good one) is that one no longer has to write &
for deps, thus the parentheses are not longer needed for multiple deps:
trait Foo: Copy {
fn foo(self);
}
trait Bar: Copy {
fn bar(self);
}
fn takes_foo(deps: impl Foo + Bar) {
deps.foo();
deps.bar();
}
But then, deps will be hardcoded to always be &
forever, and there will no longer be any chance of mutating them or taking them by value.
Have to investigate whether it will be possible to use e.g. tokio::spawn
, cloning the underlying deps. Maybe it could be done with a separate trait. trait CloneUnderlyingValue { fn clone(self); }
It appears that it will be very hard to incorporate things like Clone
into this reference-based solution. Working with T
s and &self
is much easier than working with &T
s and self
.
Putting this one ice for now.
I don't know whether this will work, but consider:
vs.
If the traits always take
self
by value, it might not be necessary to duplicate the traits when doing dependency inversion, because then we can make a newtype without reborrowing:The main reason it was necessary to duplicate the trait with the current design, was that it was impossible to make futures implement
Send
when "reborrowing" for a struct likeNewType
.NewType
had to be passed as a reference into the delegation-target, referencing the value just created on the stack, and things referencing a value owned by the stack (vs. the heap) can't be sent to another thread. IfNewType
is passed by-value, this restriction is likely lifted.