0

I want to be able to halve a generic integer type and have my function return that integer type.

use std::ops::*;

pub fn half_nonnegative<I: Shr<i32>>(n: I) -> <I as std::ops::Shr<i32>>::Output {
    n >> 1
}

pub fn half_nonnegative_input_type_same_as_output<I: Shr<i32>>(n: I) -> I {
    n >> 1
}

The first function halves my integer, but potentially returns a different type. The second function doesn't compile. How do I constrain the second function to have the same output type as the input type?

Should I be halving in some other way? Dividing by one() + one()?

David Sanders
  • 231
  • 2
  • 7
  • 1
    `pub fn foo(n: I) -> I where I: Shr {}` – Shepmaster Aug 29 '17 at 23:57
  • @Shepmaster Are there already "meta traits" that include other traits? Something like `trait Int = Add + Sub + Mul` etc. to easily write complex generic code. – Boiethios Aug 30 '17 at 12:22
  • @Boiethios yep; that's why I linked https://stackoverflow.com/q/37296351/155423 as a duplicate — it's often the next question asked. – Shepmaster Aug 30 '17 at 12:39

0 Answers0