【发布时间】:2018-12-30 12:06:40
【问题描述】:
我有以下问题(简化了一点)。
有一个 trait 提供了一组不使用 self 的函数:
pub trait ImageFormat {
fn write(data: Vec<[u8; 3]>, path: &str, ...) -> io::Result<()>;
...
}
有几个实现。
还有一个使用该特征的函数的结构:
pub struct Images<T: ImageFormat> {
path: String,
...
}
impl<T> Images<T> where T: ImageFormat {
pub fn setup(path: &str, ...) -> Images<T> {
Images {
path: String::from(path),
...
}
}
fn write(&mut self, data: Vec<[u8; 3]>, ...) -> io::Result<()> {
T::write(data, &self.path[..], ...)
}
...
}
这不会编译,因为该结构没有 T 类型的字段。 如果我这样做,它会起作用,但感觉就像一个黑客:
pub struct Images<T: ImageFormat> {
_image_format: Option<T>,
path: String,
...
}
impl<T> Images<T> where T: ImageFormat {
pub fn setup(path: &str, ...) -> Images<T> {
Images {
_image_format: None,
path: String::from(path),
...
}
}
...
}
有什么惯用的方法吗?
【问题讨论】:
-
如果结构不需要
T,为什么不直接写“结构图像”?请描述更多你想要什么。如果你真的想“强制”它,你可以使用phamtom data,但我觉得你不应该在你的情况下使用它。 -
结构体不需要T,但是像write on Images这样的方法确实需要它。在实践中我需要的只是类型,因为这些函数不使用 self.幻象数据似乎正是我想要的。
-
这并没有添加信息,我仍然认为您使用了不好的工具来解决您的问题。
标签: rust