0

Given this function,

fn incr<A: std::ops::AddAssign>(mut foo: A) -> A {
    foo += A::from(1);
    foo
}

I'm getting,

error[E0308]: mismatched types
 --> src/lib.rs:2:20
  |
1 | fn incr<A: std::ops::AddAssign>(mut foo: A) -> A {
  |         - this type parameter
2 |     foo += A::from(1);
  |                    ^ expected type parameter `A`, found integer
  |
  = note: expected type parameter `A`
                       found type `{integer}`
  = help: type parameters must be constrained to match other types
  = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

How can I make this work?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • Generally you should use `into()`, this make the error more clear https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=23eb043e2af9c8f31f53d0a1e1b008f8 or complete form... https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=df2e428f38c4598c080751d72164fe4a very verbose – Stargateur Apr 29 '20 at 00:37

1 Answers1

2

You need to specify that A has a trait bound that requires that it implements From<u8>:

fn incr<A: std::ops::AddAssign + From<u8> > (mut foo: A) -> A {
    foo += A::from(1);
    foo
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468