作为一项练习,我正在尝试创建一个温度单位库。
目前,以下代码无法编译,错误信息对我来说不清楚。问题似乎是类型冲突。
目前,以下代码无法编译,错误信息对我来说不清楚。问题似乎是类型冲突。
type Fahrenheit = f64;
type Celcius = f64;
type Kelvin = f64;
trait TemperatureUnit {
fn to_kelvin(&self) -> Kelvin;
}
impl TemperatureUnit for Fahrenheit {
fn to_kelvin(&self) -> Kelvin {
(*self + 459.67) * 5/9
}
}
impl TemperatureUnit for Celcius {
fn to_kelvin(&self) -> Kelvin {
*self + 273.15
}
}
impl TemperatureUnit for Kelvin {
fn to_kelvin(&self) -> Kelvin {
*self
}
}
错误:
error[E0119]: conflicting implementations of trait `TemperatureUnit` for type `f64`
--> src/lib.rs:18:1
|
12 | impl TemperatureUnit for Fahrenheit {
| ----------------------------------- first implementation here
...
18 | impl TemperatureUnit for Celcius {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `f64`
error[E0119]: conflicting implementations of trait `TemperatureUnit` for type `f64`
--> src/lib.rs:24:1
|
12 | impl TemperatureUnit for Fahrenheit {
| ----------------------------------- first implementation here
...
24 | impl TemperatureUnit for Kelvin {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `f64`
我是 Rust 的新手,也许这不是实现编译器强制类型安全的单位转换的正确方法。
#[repr(transparent)]
:据我所知,今天它实际上是相同的,而且当不需要时,我期望默认表示更具性能。 - Chayim FriedmanFahrenheit -> f64
和一个f64 -> Fahrenheit
的映射,它们互为反函数。 - Silvio Mayolo