反射的惯用替代方案 [英] Idiomatic alternative to reflection

查看:43
本文介绍了反射的惯用替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据配置字符串选择摘要算法(来自 rust-crypto).比如说,在 Python 或 JavaScript 中,我可能会使用反射来解决这个问题:

I am trying to select a digest algorithm (from rust-crypto) based on a configuration string. In Python or JavaScript, say, I'd probably use reflection to get at this:

getattr(Digest, myAlgorithm)

...但是根据我对 Google 的了解,这不是 Rust 等语言的最佳实践(而且我没有找到有关如何完成的详细信息).我最初的想法是使用模式匹配:

...but from what I've been able to Google, this isn't best practice in a language such as Rust (plus I've found no details on how it could be done). My initial thought was to use a pattern match:

let mut digest = match myAlgorithm {
  "sha256" => Sha256::new(),
  ...
};

然而,这不起作用,因为虽然匹配的所有分支都实现了相同的特征,但它们最终是不同的类型.此外,假设有办法解决这个问题,在代码中手动枚举所有这些选项会很麻烦.

However, this doesn't work because, while all the branches of the match implement the same trait, they're ultimately different types. Moreover, presuming there were a way around this, it's a lot of hassle to manually enumerate all these options in the code.

在 Rust 中执行此操作的正确方法是什么?

What's the right way to do this in Rust?

推荐答案

由于所有算法都实现了相同的特征 Digest,它提供了您需要的一切,您可以将所有算法装箱并将它们转换为一个常见的Box:

Since all the algorithms implement the same trait Digest, which offers everything you need, you can box all the algorithms and convert them to a common Box<Digest>:

let mut digest: Box<Digest> = match my_algorithm {
    "sha256" => Box::new(Sha256::new()),
    ...
};

现在您不再知道类型是什么,但您仍然知道它是 Digest.

Now you don't know anymore what the type was, but you still know it's a Digest.

python 和 javascript 在后台为您执行装箱(动态堆分配).Rust 对此类事情非常挑剔,因此要求您明确说明您的意思.

The python and javascript do the boxing (dynamic heap allocation) for you in the background. Rust is very picky about such things and therefor requires you to explicitly state what you mean.

在 Rust 中进行反射以便能够枚举实现 trait 的范围内的所有类型会很有趣,但是这样的系统需要在 Rust 编译器和 Rust 社区成员的大脑中付出相当多的努力.不要指望它很快.

It would be interesting to have reflection in Rust to be able to enumerate all types in scope that implement a trait, but such a system would require quite some effort in the rust compiler and in the brains of of the rust community members. Don't expect it any time soon.

这篇关于反射的惯用替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆