How do I write a generic square function that works for f32, f64, i32, isize, usize ?

Here's what I have so far:

```
pub fn sqr<T: std::ops::Mul>(x: T) -> T {
x * x
}
```

How do I write a generic square function that works for f32, f64, i32, isize, usize ?

Here's what I have so far:

```
pub fn sqr<T: std::ops::Mul>(x: T) -> T {
x * x
}
```

1 Like

The trait result is generic too, so if you want to restrict this to the same type, use `Mul<Output = T>`

. You'll also need `Copy`

to use `x`

twice, or else switch the constraints to multiply by reference.

```
where for<'a, 'b> &'a T: Mul<&'b T, Output = T>
```

3 Likes

Just add a `T: Copy + Mul<Output = T>`

bound and that will cover all numeric types in `std`

3 Likes

Thanks! The `Mul<Output = T>`

makes complete sense in hindsight but was not obvious at first.

You could also return `T::Output`

instead of `T`

. The issue is that the `Mul`

op allows for returning a type that's different than `Self`

(it also allows for multiplying two different types but that's obviously not an issue here).

1 Like

One common use of that with `Mul`

is to return a type that is twice the width of the input arguments

(e.g., `u32 * u32 -> u64`

).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.