1

I've got three functions with signatures like the following (slightly simplified below):

fn f<T>(f: impl Fn(&T), x : &impl ATrait<T>) {}
fn f<T>(f: impl Fn(&T), x : impl ATrait<T>) {}
fn f<T>(f: impl Fn(T), x : impl ATrait<T>) {}

Naturally as they're all named f this won't compile but is there anyway I can give them the same name through traits+impls or other methods so I can do:

f(|&e| {}, &x);
f(|&e| {}, x);
f(|e| {}, x);

and it selects the correct overload based on argument type?

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • if your function can work without consume `x` why would you need more than one version ?!? – Stargateur Jun 15 '19 at 16:02
  • The version which consumes `x` can do things like skip a full copy because we can just mutate `x`. I've simplified the functions they actually all return (the same value). They're roughly speaking like `Option.map`. – Clinton Jun 15 '19 at 16:04
  • 1
    if you need to consume the value just take by value and let the caller perform copy if needed – Stargateur Jun 15 '19 at 16:06
  • Actually there's no copies in either case it's just one creates a new object and the other modifies in place. But that's not always the case it depends on exact type of the second argument as it's a trait so the implementations can be different. – Clinton Jun 15 '19 at 16:08
  • I don't follow you, by using `impl ATrait`, you can't know the real type, that the point of this syntax. So you can't know what implementation is doing. – Stargateur Jun 16 '19 at 12:25
  • 1
    You can learn from my answer to a similar question: https://stackoverflow.com/questions/56555910/do-i-have-to-implement-a-trait-twice-when-implementing-it-for-both-reference-and/56609965#56609965 – Boiethios Jun 17 '19 at 08:59

0 Answers0