Rust 泛型中的常量值 [英] Constant values in Rust generics

查看:44
本文介绍了Rust 泛型中的常量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 语言是否支持类似于 C++ 方式的通用代码中的常量值?似乎语言 overview 没有宣传它.在 C++ 中使用常量参数化类型允许根据客户的需要创建具有不同大小的预分配缓冲区的对象(类型如 stlsoft::auto_buffer).
如果不是,那么在 Rust 中实现类似设计的最佳实践是什么?

Does Rust language support constant values in generic code similar to c++ way? Seems that the language overview doesn't advertise it. Parameterizing types with constants in C++ allows to create objects with preallocated buffers of different size depending on client's needs (types like stlsoft::auto_buffer).
If not, then what is the best practices to implement similar designs in Rust?

推荐答案

不,这在类型安全的方式下不受支持.为此,我们需要类型级别的数字文字,例如 GHC 最近添加的.

No, this is not supported in a type-safe way. We would need type-level numeric literals, like GHC recently added, for that.

但是,您可以使用 Rust 宏.使用宏,您可以创建通过任意表达式参数化的模板",包括常量,这将允许您在此处执行所需的操作.请注意,如果您现在尝试这样做,您可能会发现宏系统中的错误和限制.

However, you can use Rust macros. With a macro you can create "templates" that are parameterized over arbitrary expressions, including constants, which would allow you to do what you want here. Note that you may find bugs and limitations in the macro system if you try this at the moment.

这篇关于Rust 泛型中的常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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