常规浮点文字不起作用:
extern crate num_traits;
use num_traits::float::Float;
fn scale_float<T: Float>(x: T) -> T {
x * 0.54
}
fn main() {
let a: f64 = scale_float(1.23);
}
Run Code Online (Sandbox Code Playgroud)
extern crate num_traits;
use num_traits::float::Float;
fn scale_float<T: Float>(x: T) -> T {
x * 0.54
}
fn main() {
let a: f64 = scale_float(1.23);
}
Run Code Online (Sandbox Code Playgroud) 我编写了一个通用函数来检查给定数字是否为偶数:
use std::ops::Rem;
fn main() {
let x: u16 = 31;
let y: u32 = 40;
println!("x = {}, y = {}", is_even(x), is_even(y));
}
fn is_even<T: Rem<Output = T> + PartialEq>(n: T) -> bool {
n % 2 == 0
}
Run Code Online (Sandbox Code Playgroud)
它会产生编译器错误:
use std::ops::Rem;
fn main() {
let x: u16 = 31;
let y: u32 = 40;
println!("x = {}, y = {}", is_even(x), is_even(y));
}
fn is_even<T: Rem<Output = T> + PartialEq>(n: T) -> bool {
n % …Run Code Online (Sandbox Code Playgroud) 下面是一个通用类型Foo。如何正确实现该addOne方法:
struct Foo<T> {
n: T,
}
impl<T> Foo<T> {
fn addOne(self) -> T {
self.n + 1
}
}
fn main() {
let a = Foo { n: 5 };
println!("{}", a.addOne());
}
Run Code Online (Sandbox Code Playgroud)
我期望输出为6,但是此代码无法编译:
struct Foo<T> {
n: T,
}
impl<T> Foo<T> {
fn addOne(self) -> T {
self.n + 1
}
}
fn main() {
let a = Foo { n: 5 };
println!("{}", a.addOne());
}
Run Code Online (Sandbox Code Playgroud) 我越来越熟悉 Rust 泛型,但我不知道出了什么问题。
use std::collections::BTreeMap;
fn frequency<T: Ord + Clone>(vec: &Vec<T>) -> BTreeMap<T, u32> {
let mut movie_reviews = BTreeMap::new();
let mut vec_ = Vec::new();
vec.push(1);
movie_reviews
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它需要 type T:
use std::collections::BTreeMap;
fn frequency<T: Ord + Clone>(vec: &Vec<T>) -> BTreeMap<T, u32> {
let mut movie_reviews = BTreeMap::new();
let mut vec_ = Vec::new();
vec.push(1);
movie_reviews
}
Run Code Online (Sandbox Code Playgroud) 我有以下代码片段:
use num_bigint::*; // 0.2.2
use num_traits::*; // 0.2.8
use std::ops::*;
fn xgcd(b: &BigInt, a: &BigInt) -> (BigInt, BigInt, BigInt) {
let mut x0: BigInt = One::one();
let mut x1: BigInt = Zero::zero();
let mut y0: BigInt = Zero::zero();
let mut y1: BigInt = One::one();
let mut q = 0;
while a != Zero::zero() {
q = b.div(a);
b = a;
a = &b.rem(a);
x0 = x1;
x1 = x0 - q * x1;
y0 = y1;
y1 = y0 …Run Code Online (Sandbox Code Playgroud)