Ray*_*bel 1 generics syntax struct tuples rust
我正在尝试实现自定义集.这可以编译没有问题:
struct CustomSet {}
impl CustomSet {
pub fn new() -> CustomSet {
CustomSet {}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将单元类型(空元组)添加到CustomSet类型中时,它将无法编译.
struct CustomSet<()> {}
impl CustomSet<()> {
pub fn new() -> CustomSet<()> {
CustomSet {}
}
}
Run Code Online (Sandbox Code Playgroud)
以下错误
error: expected one of `>`, identifier, or lifetime, found `(`
--> src/lib.rs:1:18
|
1 | struct CustomSet<()> {}
| ^ expected one of `>`, identifier, or lifetime here
Run Code Online (Sandbox Code Playgroud)
如何返回具有单位数据类型的结构?我做错了什么?
CustomSet<()>只有CustomSet使用类型参数定义时,该类型才有意义.类型参数是变量,而不是另一种类型,因此您的定义实际上没有意义.相反,您需要使用变量定义它:
struct CustomSet<T> {}
Run Code Online (Sandbox Code Playgroud)
这意味着CustomSet为任何可能的类型定义T(必须注意类型Sized,大多数类型都是如此).
现在,上面的定义不会起作用,因为Rust会抱怨你没有T在类型中使用变量.你不使用的变量有什么意义?
正如hellow所说,你可以使用PhantomData,但这更像是一种解决方法,当你需要变量但实际上并不需要因某些原因使用它时.由于您正在实现集合,因此您需要使用T以便在某处存储值:
struct CustomSet<T> {
data: Vec<T>,
}
Run Code Online (Sandbox Code Playgroud)
这种类型的行为仍然可以实现所有可能的 T,而不仅仅是(),为您提供大量的代码重用:
impl<T> CustomSet<T> {
pub fn new() -> CustomSet<T> {
CustomSet {
data: Vec::new(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
只有当你真正使用你需要约束的类型T时:
let my_set: CustomSet<()> = CustomSet::new();
Run Code Online (Sandbox Code Playgroud)
在实际程序中通常不需要该类型注释,因为它将从使用中推断出来.例如,如果您提供了insert方法CustomSet,则可以像下面这样使用它:
// type annotation not needed because it will be inferred from the next line
let mut my_set = CustomSet::new();
my_set.insert(());
Run Code Online (Sandbox Code Playgroud)