I\'ve seen the Borrow
trait used to define functions that accept both an owned type or a reference, e.g. T
or &T
. The borrow
With the function you have you can only use a u32
or a type that can be borrowed as u32
.
You can make your function more generic by using a second template argument.
fn foo>(value: N) -> T {
*value.borrow()
}
This is however only a partial solution as it will require type annotations in some cases to work correctly.
For example, it works out of the box with usize
:
let v = 0usize;
println!("{}", foo(v));
There is no problem here for the compiler to guess that foo(v)
is a usize
.
However, if you try foo(&v)
, the compiler will complain that it cannot find the right output type T
because &T
could implement several Borrow
traits for different types. You need to explicitly specify which one you want to use as output.
let output: usize = foo(&v);