相關(guān)常量

2018-08-12 22:04 更新

相關(guān)常量

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

#![feature(associated_consts)]

trait Foo {
const ID: i32;
}

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

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

任何 Foo 的實(shí)現(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 { }

默認(rèn)的值可以采用如下實(shí)現(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);
}

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

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

#![feature(associated_consts)]

struct Foo;

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)