我怎样才能做到这一点?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试的所有东西总是返回类型Object而不是使用的特定类型.
编者注:此代码示例来自1.0之前的Rust版本,并且在语法上不是有效的Rust 1.0代码.此代码的更新版本会产生不同的错误,但答案仍包含有价值的信息.
在下列情况下,似乎我们无法测试相等性.为什么是这样?有解决方法吗?(我正在使用Rust 0.11).
trait A: PartialEq {}
#[deriving(PartialEq)]
enum T {Ta, Tb}
impl A for T {}
fn main() {
assert!(Ta == Ta);
assert!(Ta != Tb);
assert!(some_fn(&Ta, &Ta));
assert!(!some_fn(&Ta, &Tb));
}
fn some_fn(an_a: &A, another_a: &A) -> bool {
an_a == another_a
// ERROR ^~~~~~~~~~~~ binary operation `==` cannot be applied to type `&A`
}
fn another_fn(an_a: &A + PartialEq, another_a: &A + PartialEq) -> bool {
// ERROR: ^~~~~~~~~ only the builtin traits can be used as closure …Run Code Online (Sandbox Code Playgroud) 我希望能够使用各种不同类型作为 a 中的键HashMap,所有这些都可以实现Hash。这似乎应该是可能的:从阅读文档来看,似乎每个Hasher都会产生一个u64结果,因此它们最终会简化为通用类型。实际上我想做的是:
use std::{collections::HashMap, hash::Hash};
fn x(_: HashMap<Box<dyn Hash>, ()>) {}
Run Code Online (Sandbox Code Playgroud)
我不被允许这样做:
error[E0038]: the trait `std::hash::Hash` cannot be made into an object
--> src/lib.rs:3:9
|
3 | fn x(_: HashMap<Box<dyn Hash>, ()>) {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::hash::Hash` cannot be made into an object
Run Code Online (Sandbox Code Playgroud)
似乎我可以创建一个Hasher(例如RandomState),用它来手动计算哈希值,然后将u64结果存储在 a 中HashMap<u64, _>,但这似乎过于复杂。我不想再次获取键值,我只需要能够比较哈希值。有HashMap我不知道的替代方案吗?或者我以完全错误的方式看待这个问题?