我正在尝试创建一个生成 a 的宏,struct该宏提供一组传递到宏中的方法。例如,调用:
create_impl!(StructName, fn foo() -> u32 { return 432 })
Run Code Online (Sandbox Code Playgroud)
应该生成一个StructName提供方法的空结构foo()。
我最初尝试使用item宏 arg 类型。但是,当我尝试item在规则中使用 an 时,出现以下编译器错误:
create_impl!(StructName, fn foo() -> u32 { return 432 })
Run Code Online (Sandbox Code Playgroud)
是否可以使用item参数以这种方式在生成的结构中定义方法?我有什么遗漏的吗?
这是我定义的完整宏:
macro_rules! create_impl {
($struct_name:ident, $($function:item),*) => {
struct $struct_name {
}
impl $struct_name {
// This is the part that fails.
$($function)*
}
};
}
Run Code Online (Sandbox Code Playgroud) 在C++ 11中,您可以将泛型类型衰减为值类型,删除引用/右值语义和cv限定符,例如
decay<int>::type // type is `int`
decay<const int&>::type // type is `int`
decay<int&&>::type // type is `int`
Run Code Online (Sandbox Code Playgroud)
是否有一种已知的机制可以在Rust中实现相同的功能,即剥离引用修饰符,生命周期和mut限定符?例如:
decay<u32>::type <--- type is `u32`
decay<&u32>::type <--- type is `u32`
decay<&mut u32>::type <--- type is `u32`
decay<&static u32>::type <--- type is `u32`
Run Code Online (Sandbox Code Playgroud)
对于背景,我正在尝试编写一个宏,该宏生成一个struct存储宏匹配的一堆函数参数的值.例如,宏可能包含args foo: i32, bar: &Vec<String>,结果结构应该是:
struct GeneratedStruct {
foo: i32,
bar: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud) 我有以下结构:
pub struct Foo<T> {
some_value: T,
}
impl<T> Foo<T> {
pub fn new(value: T) -> Self {
Self { some_value: value }
}
}
// Implement `Default()`, assuming that the underlying stored type
// `T` also implements `Default`.
impl<T> Default for Foo<T>
where
T: Default,
{
fn default() -> Self {
Self::new(T::default())
}
}
Run Code Online (Sandbox Code Playgroud)
Foo::default()如果T实现Default,我希望可用,否则不可用。
是否可以在 Rust 中指定“条件实现”,当且仅当满足某个泛型类型特征约束时,我们才实现特征?如果不满足约束,则不会实现目标特征(Default在本例中)并且没有编译器错误。
换句话说,是否可以通过以下方式使用上面的通用结构?
fn main() {
// Okay, because `u32` implements `Default`.
let foo …Run Code Online (Sandbox Code Playgroud) 是否有一种惯用的Rust方法来绑定函数参数并生成一个新函数?
例如,假设我有以下功能:
fn eq(a: i32) -> Box<Fn(i32) -> bool> {
let target = a; // copy
Box::new(move |value| value == target)
}
fn evaluate(func: Box<Fn(i32) -> bool>, value: i32) -> bool {
func(value)
}
Run Code Online (Sandbox Code Playgroud)
Box机制使用的机制是将eq参数绑定到函数中以供使用evaluate吗?例如:
let is_42 = eq(42);
assert_eq!(true, evaluate(is_42, 42));
Run Code Online (Sandbox Code Playgroud)
还有生命的问题.我想知道延长targetin 的生命周期的正确语义是什么eq(),所以它的生命周期与盒装函数的生命周期有关.