Rustのstruct内で共通の定数を使いたい
implにconstと書いて定義できる。
定義方法
code:rs
struct MyStruct {
x: i32
}
impl MyStruct {
const MY_CONST: u32 = 8;
}
使い方
以下のようにMyStruct::MY_CONSTとしても良いし、MyStruct内ならSelf::MY_CONSTでアクセスできる。
code:rs
struct MyStruct {
x: i32
}
impl MyStruct {
const MY_CONST: u32 = 8;
pub fn my_func(&self) {
println!("my_func called: {}", Self::MY_CONST);
}
}
fn main() {
println!("{}", MyStruct::MY_CONST);
MyStruct{x: 1212}.my_func();
}