如何定义可以执行按位运算的整数上的泛型函数?

问题描述 投票:0回答:1

我有以下功能:

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

我可以尝试(不成功)使它在整数上通用:

extern crate num;

use num::Integer;

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

这不起作用。它会生成以下错误:

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}`

我知道有Shl trait。我是否需要使用此特性来完成这项工作?我该怎么做?

generics rust
1个回答
2
投票

我是否需要使用[Shl]来完成这项工作?

是。你还需要确保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
}
© www.soinside.com 2019 - 2024. All rights reserved.