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?

1

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.