gpt4 book ai didi

module - 如何从特定模块创建所有装饰函数的向量?

转载 作者:行者123 更新时间:2023-11-29 08:15:32 25 4
gpt4 key购买 nike

我有一个文件 main.rs 和一个文件 rule.rs。我想在 rule.rs 中定义要包含在 Rules::rule 向量中的函数,而不必将它们一一推送。我更喜欢一个循环来插入它们。

ma​​in.rs:

struct Rules {
rule: Vec<fn(arg: &Arg) -> bool>,
}

impl Rules {
fn validate_incomplete(self, arg: &Arg) -> bool {
// iterate through all constraints and evaluate, if false return and stop
for constraint in self.incomplete_rule_constraints.iter() {
if !constraint(&arg) {
return false;
}
}
true
}
}

rule.rs:

pub fn test_constraint1(arg: &Arg) -> bool {
arg.last_element().total() < 29500
}

pub fn test_constraint2(arg: &Arg) -> bool {
arg.last_element().total() < 35000
}

Rules::rule 应该用 test_constraint1test_constraint2 填充。

在 Python 中,我可以在要包含在 Vec 中的约束上方添加装饰器 @rule_decorator,但我在 Rust 中看不到等效项.

在 Python 中,我可以使用 dir(module) 查看所有可用的方法/属性。

Python 变体:

class Rules:

def __init__(self, name: str):
self.name = name
self.rule = []

for member in dir(self):
method = getattr(self, member)
if "rule_decorator" in dir(method):
self.rule.append(method)

def validate_incomplete(self, arg: Arg):
for constraint in self.incomplete_rule_constraints:
if not constraint(arg):
return False
return True

使用 rule.py 文件:

@rule_decorator
def test_constraint1(arg: Arg):
return arg.last_element().total() < 29500

@rule_decorator
def test_constraint1(arg: Arg):
return arg.last_element().total() < 35000

所有带有 rule_decorator 的函数都被添加到 self.rule 列表中,并由 validate_incomplete 函数检查。

最佳答案

Rust 没有与 Python 相同的反射特性。特别是,您不能在运行时遍历模块的所有功能。至少你不能用内置工具做到这一点。可以编写所谓的过程宏,它可以让您将自定义属性添加到您的函数中,例如#[rule_decorator] fn foo() { ... }。使用 proc 宏,您几乎可以做任何事情。

但是,为此使用 proc 宏是过度设计的(在我看来)。对于您的情况,我将简单地列出要包含在您的向量中的所有函数:

fn test_constraint1(arg: u32) -> bool {
arg < 29_500
}
fn test_constraint2(arg: u32) -> bool {
arg < 35_000
}

fn main() {
let rules = vec![test_constraint1 as fn(_) -> _, test_constraint2];

// Or, if you already have a vector and need to add to it:
let mut rules = Vec::new();
rules.extend_from_slice(
&[test_constraint1 as fn(_) -> _, test_constraint2]
);
}

关于这段代码的几点说明:

  • 我用u32替换了&Arg,因为它与问题没有任何关系。请省略 StackOverflow 问题中不必要的细节。
  • 我在数字文字中使用了 _ 以提高可读性。
  • 很遗憾,奇怪的 as fn(_) -> _ 强制转换是必要的。您可以在 this question 中阅读更多相关信息.

关于module - 如何从特定模块创建所有装饰函数的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com