W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
使用 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)。struct
的impl
塊也可以很好的工作,如下:
#![feature(associated_consts)]
struct Foo;
impl Foo {
pub const FOO: u32 = 3;
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: