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