The trait bound in baz
is unnecessarily strong for when flag=true
, in which case we only require Foo
.
I would like to have that baz
can accept where T: Foo
and only enforce the Bar
bound when flag=false
.
trait Foo {}
trait Bar: Foo {}
fn foo<T>(t: T) where T: Foo {}
fn bar<T>(t: T) where T: Bar {}
fn baz<T>(t: T, flag: bool)
where T: Bar
{
if flag {
foo(t);
} else {
bar(t);
}
}
Changing the bound to where T: Foo
will of course not compile:
bar(t)
.........^ the trait
Bar
is not implemented forT
Introducing a new function quux
which can be called by !Bar
types is probably the solution I'll have to accept.
But is there any way both Bar
and !Bar
types could both access a single function baz
?
A solution which involves a runtime panic if flag=false
and T: !Bar
is acceptable.
baz()
function already exists with theFoo
trait bound, adding a new function with aBar
bound shouldn't break any existing code. – Sven MarnachBar
trait bound, I've just pasted theFoo
form of the trait bound which doesn't compile. – spherebaz
, from the currentBar
to theFoo
shown in the question (which doesn't compile)? And by "breaking" the API you mean breaking it up into two functions, not breaking as in making a backward-incompatible change? – user4815162342T: Foo
and another forT: Bar
(which is currently not allowed due to overlap). Thenbaz
would trivially call the method from that trait which would resolve to the right thing. – user4815162342