繁体   English   中英

如何定义可以执行按位运算的整数上通用的Rust函数?

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

我有以下功能:

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特质 我需要使用此特征来使它起作用吗? 我该怎么做?

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

是。 您还需要确保操作结果是正确的类型

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM