相關常量

2018-08-12 22:04 更新

相關常量

使用 associated_consts 功能,用戶可以采用如下方式來定義常量:

#![feature(associated_consts)]

trait Foo {
const ID: i32;
}

impl Foo for i32 {
const ID: i32 = 1;
}

fn main() {
assert_eq!(1, i32::ID);
}

任何 Foo 的實現(xiàn)都必須定義 ID. 如果沒有定義:

#![feature(associated_consts)]

trait Foo {
const ID: i32;
}

impl Foo for i32 {
}

上述代碼出現(xiàn)下面的提示:

error: not all trait items implemented, missing:ID[E0046] impl Foo for i32 { }

默認的值可以采用如下實現(xiàn):

#![feature(associated_consts)]

trait Foo {
const ID: i32 = 1;
}

impl Foo for i32 {
}

impl Foo for i64 {
const ID: i32 = 5;
}

fn main() {
assert_eq!(1, i32::ID);
assert_eq!(5, i64::ID);
}

正如用戶看到那樣,當實現(xiàn) Foo 的時候,用戶可以不實現(xiàn) i32,它就會使用默認值。至于 i64,我們也可以增加我們自己的定義。

相關常量并不是必須與一個特性相關。structimpl塊也可以很好的工作,如下:

#![feature(associated_consts)]

struct Foo;

impl Foo {
pub const FOO: u32 = 3;
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號