gpt4 book ai didi

generics - 如何定义对可以进行按位运算的整数通用的 Rust 函数?

转载 作者:行者123 更新时间:2023-11-29 08:27:07 24 4
gpt4 key购买 nike

我有以下功能:

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 .我需要使用这个特性来完成这项工作吗?我该怎么做?

最佳答案

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

是的。您还需要确保 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
}

关于generics - 如何定义对可以进行按位运算的整数通用的 Rust 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com