user8370684
user8370684

Reputation:

How to define Rust function that's generic on integers that can do bitwise operations?

I have the following function:

fn f1(n: u8) -> u16 {
    1 << n
}

I can try to (unsuccessfully) make it generic on integers:

extern crate num;

use num::Integer;

fn f1<T: Integer>(n: u8) -> T {
    1 << n
}

This doesn't work. It generates the following error:

error[E0308]: mismatched types
 --> src/main.rs:6:5
  |
5 | fn f1<T: Integer>(n: u8) -> T {
  |                             - expected `T` because of return type
6 |     1 << n
  |     ^^^^^^ expected type parameter, found integral variable
  |
  = note: expected type `T`
             found type `{integer}`

I understand there is the Shl trait. Do I need to use this trait to make this work? How would I do this?

Upvotes: 0

Views: 365

Answers (1)

Shepmaster
Shepmaster

Reputation: 430791

Do I need to use [Shl] to make this work?

Yes. You also need to make sure the result of the operation is the right type:

extern crate num;

use num::Integer;
use std::ops::Shl;

fn f1<T>(n: u8) -> T
where
    T: Integer + Shl<u8, Output = T>,
{
    T::one() << n
}

Upvotes: 2

Related Questions