问题描述
我想比赛,例如一个实现特定特征的ident
类型,我该怎么做?
I want to match, e.g. an ident
's type to implement a certain trait, how would I do that?
这是(不完整的)代码中的基本概念:
Here the basic idea in (incomplete) code:
macro_rules! has_trait {
($ ($t : ty), ($x : ident),) => {
}
}
fn trait_test() {
let a = vec![1, 2, 3];
let b = 42;
let a_iteratable = has_trait!(IntoIterator, a);
let b_iteratable = has_trait!(IntoIterator, b);
println!("{:?} iterable? {}", a, a_iteratable);
println!("{:?} iterable? {}", b, b_iteratable);
}
我不能为如何说具有特征Foo
的任何类型"而烦恼.
I cannot wrap my head around how to say "any type which has trait Foo
".
我看到2种解决问题的方法:
I see 2 options how to tackle the problem:
- 找到一个匹配表达式,该表达式匹配具有特征
$t
的任何类型,并在匹配时简单地返回true,否则(如何工作?)为false. - 在任何类型的匹配项的主体中,使用一些代码来确定特征
$t
是否由$x
类型实现.
- Find a match expression which matches any type with trait
$t
and simply return true on match, else (how works else?) false. - In the body of the match of any type, use some code to determine if trait
$t
is implemented by the type of$x
.
我看不到如何做这两种选择.
I cannot see how to do either of both options.
这甚至可以做到吗?
推荐答案
您基本上想要的是静态(或编译时)反射:根据类型系统,在编译时分配值以在运行时使用.例如,在D甚至C ++中,这都是可能的,但在Rust中是不可能的.
What you basically want is static (or compile-time) reflection:Assigning values at compile-time, depending on the type system, to use at run-time.This is possible in for example D or even C++, but not in Rust.
Rust不允许模板专门化或编译时值作为通用参数,也没有像D这样的静态反射功能.
Rust does not allow template specialisation or compile-time values as generic parameters, nor does it have static reflection capabilities like D.
这篇关于是否可以编写Rust宏"has_trait!(< type>,< ident> |< expr>))"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!