简体   繁体   English

如何在Rust中定义关联的const或类型别名?

[英]How can I define an associated const or type alias in Rust?

Basically, I just want "shortcuts": 基本上,我只想要“快捷方式”:

impl Foo {
    const c : i32 = 42;
    type V = i32;
    fn bar() -> V { c }
}

But the compiler complains with: 但是编译器抱怨:

error: associated constants are experimental (see issue #29646)

As mentioned in the error message, associated constants ( const c: i32 = 42 ) are experimental. 如错误消息中所述,相关的常数( const c: i32 = 42 )是实验性的。

This means that, unless you switch to a nightly compiler and enable the feature, you cannot have constants nested inside implementations or traits. 这意味着,除非切换到夜间编译器启用该功能,否则不能将常量嵌套在实现或特征内。

You can, however, have constants at module scope: 但是,您可以在模块范围内使用常量:

const C: i32 = 42;

If you fix this, you will get to the next error: associated types are only allowed in traits and their implementation, not in "inherent" implementations. 如果解决此问题,将出现下一个错误:关联类型仅允许在特征及其实现中使用,而不能在“固有”实现中使用。

Once again, the work-around is to pull out the type alias at module scope: 再一次,解决方法是在模块作用域中提取类型别名:

type V = i32;

The following code compiles: 以下代码编译:

const C: i32 = 42;
type V = i32;

struct Foo;

impl Foo {
    fn bar() -> V { C }
}

and with C and V being private (only accessible within the module) they do not leak. 并且CV是私有的(只能在模块内访问),它们不会泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM