Generics 如果我知道它';有可能吗?
我有一个通用的Generics 如果我知道它';有可能吗?,generics,rust,Generics,Rust,我有一个通用的struct,只有一个字段,只能是i32或f32 trait MyInt { fn blank(); } impl MyInt for i32 { fn blank() { unimplemented!() } } impl MyInt for f32 { fn blank() { unimplemented!() } } struct MyStruct<T> where T: MyInt {
struct
,只有一个字段,只能是i32
或f32
trait MyInt {
fn blank();
}
impl MyInt for i32 {
fn blank() {
unimplemented!()
}
}
impl MyInt for f32 {
fn blank() {
unimplemented!()
}
}
struct MyStruct<T> where T: MyInt {
field: T
}
impl<T> MyStruct<T> where T: MyInt {
fn new(var: T) -> MyStruct<T> {
MyStruct {
field: var
}
}
}
您只需将强制转换作为方法添加到您的
MyInt
trait:
trait MyInt {
fn to_f32_lossy(self) -> f32;
}
impl MyInt for i32 {
fn to_f32_lossy(self) -> f32 {
self as f32
}
}
impl MyInt for f32 {
fn to_f32_lossy(self) -> f32 {
self
}
}
你说得对,
因为
只适用于具体类型
使用From
或Into
特性进行转换是一种很好的方法,但这些特性并没有在i32->f32转换中实现。原因很可能是,正如Matthieu M.所说,这是一种潜在的有损转换
您必须使用f64
而不是f32
trait MyInt {
fn blank();
}
impl MyInt for i32 {
fn blank() {
unimplemented!()
}
}
impl MyInt for f32 {
fn blank() {
unimplemented!()
}
}
struct MyStruct<T> where T: MyInt {
field: T
}
impl<T> MyStruct<T> where T: MyInt {
fn new(var: T) -> MyStruct<T> {
MyStruct {
field: var
}
}
}
我建议将这一特点改为:
trait MyInt: Copy + Into<f64> {
fn blank();
}
您确实意识到,许多
i32
值不能(准确地)表示为f32
,因为根据IEEE标准f32
只有23位尾数(因此它可以表示一个假设的i24
,但不能更多)。感谢您的回复。你能解释一下这句话的意思吗?实现MyInt
trait的类型也应该实现Copy
和到trait中?@ehsisthatswerd:是的,:
后面的部分详细说明了类型必须满足的要求,才能实现MyInt
;这还意味着,当使用实现MyInt
的类型时,您知道它必须实现这些其他特性。
fn to_f64(&self) -> f64 {
self.field.into()
}