Addition is not defined for every type. For a type parameter, how should the compiler know that it makes sense for your type to be added? You have to add trait bounds that describe what operations are defined on each generic type parameter. For addition, that's the std::ops::Add trait.
you can modify your code following this suggestion, (i.e., adding a trait bound, as already mentioned above, but using a different syntax). The following code run just fine, as suggested by the compiler:
You can do that without having to abstain from the better ergonomics offered by Add (namely that you can use the + operator) by making Add a supertrait of your trait:
use std::ops::Add;
trait MyTrait: Add<Self, Output = Self> + Sized {}
impl MyTrait for u8 {}
impl MyTrait for u32 {}
fn add<UInt: MyTrait>(num_0: UInt, num_1: UInt) -> UInt
{
num_0 + num_1
}
fn main() {
assert_eq!(add(1_u8, 5), 6);
assert_eq!(add(1_u32, 5), 6);
// error, because u64 does not implement MyTrait
//assert_eq!(add(1_u64, 5), 6);
}
It means that whatever type gets subsituted for the type variable UInt, it must have an Add impl where both the RHS and the result have the same type as itself. This can be deduced from the documentation of the relevant trait.
off-topic: I've been using ChatGPT for different tasks (including code generation of Python code). I am genuinely interested in knowing more about how did ChatGPT helped you a lot?