Greetings everyone!
Apologies for the dumb question. I just started the Rust official book, and everything seems so hard now (compared to Python, there is a whole new world in Rust). I need your help with generics. I want to write a simple function that adds 5 to whatever type is put into the function (integers and float obviously).
use std::ops::Add;
fn main() {
let mut x1 = 20;
let res= add_two(&x1);
println!("The result is {}", res);
}
fn add_two <'a, T>(first: &'a T) -> &'a T
where T: Add
{
return first + 5;
}
If I understood it correctly, in case I need to add something to this has to implement the add trait (correct me if I'm wrong).
When I run the code the compiler told me "error[E0369]: cannot add {integer}
to &T
".
help: consider extending the where
clause, but there might be an alternative better way to express this requirement.
Could you please help with explanations "on fingers" how to implement that function correctly?
The compiler offers me to add &T: Add<&i32, Output = &'a T> however, I have to understand why I need to do so and whether the simpler option exists in this case.
Thank you all in advance!