簡體   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