gpt4 book ai didi

rust - 如何在泛型中使用 `Num::one()`?

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

我正在尝试实现通用向量的normalize 功能,这需要我使用等同于self.mulf(1.0/self.length()) 的东西.

但是,我无法使用 Float::one() 笼统地指定我需要任何可能类型的 float 中的“一个”。

如果在泛型函数中使用后者可以正常工作,但不能在泛型类型中使用。

如何在泛型类型中使用 Num::one()

代码

下面的代码应该作为一个例子来展示我已经尝试过的东西。此外,我相信已经在通用特征实现中看到使用 Float::one() 的代码,但我不想“特征化”我的向量以使其尽可能简单。

use std::num::Float;

#[derive(Debug, PartialEq, Eq, Copy)]
pub struct Vector<T: Float> {
x: T,
y: T,
z: T,
}

impl<T: Float> Vector<T> {
#[inline(always)]
fn mulfed(&self, m: T) -> Vector<T> {
Vector { x: self.x * m, y: self.y * m, z: self.z * m }
}

fn dot(&self, r: &Vector<T>) -> T {
self.x * r.x + self.y * r.y + self.z * r.z
}

// "the type of this value must be known in this context"
// fn normalized(&self) -> Vector<T> {
// self.mulfed(Float::one() / self.dot(self).sqrt())
// }
// "the type of this value must be known in this context"
// fn normalized(&self) -> Vector<T> {
// self.mulfed(Float::one() as T / self.dot(self).sqrt())
// }

// "too many type parameters provided: expected at most 0 parameter(s), found 1 parameter(s)"
// As Float is a trait, this can be expected to not work I guess. It should be able to
// use Float::one() from within another trait though.
// fn normalized(&self) -> Vector<T> {
// self.mulfed(Float::one::<T>() / self.dot(self).sqrt())
// }
}

fn gimme_one<T: Float>() -> T {
Float::one()
}

#[test]
fn one() {
// But this works !!
let v: f32 = gimme_one();
assert_eq!(v, 1.0f32);
}

我正在使用 rustc 1.0.0-nightly (458a6a2f6 2015-01-25 21:20:37 +0000)

最佳答案

这是一个 bug in type inference .在错误修复之前,您可以使用完全指定的 UFCS 形式:

fn normalized(&self) -> Vector<T> {
self.mulfed(<T as Float>::one() / self.dot(self).sqrt())
}

更好的是,您可以使用 Float::recip :

fn normalized(&self) -> Vector<T> {
self.mulfed(self.dot(self).sqrt().recip())
}

关于rust - 如何在泛型中使用 `Num::one()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28285085/

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