saba1024のブログ

どうでも良い思いついた事とかプログラミング関係のメモとか書いていきます。

Rust 1.20の新機能 Associated constants(関連定数)

概要

最近Rustの勉強をしています。
今まで基本的にJavaApache Groovy畑で生きてきたので新しい概念が多くかなり苦戦しています。
さて、8月31日にRust1.20がリリースされました。この新しいバージョンでAssociated constants(関連定数)という機能が追加されました。
ざっくり言うと、既にあったAssociated functions(関連関数)の定数版という感じのようです。
まだまだ自身を持ってどうこう言えるほどRustを理解できているわけではありませんが、実際に使ってみたので以下のそのサンプルコードを示します。

実際のコード

// Associated constants with struct
struct Struct;
impl Struct {
    // associated constants
    const PI:f32 = 3.14;

    fn double(&self) -> f32 {
        Self::PI * 2.0
    }
}

// Associated constants with trait.
trait Trait {
    // associated constants
    const PI:f32;

    fn double(&self) -> f32 {
        Self::PI
    }
}
struct Circle;
impl Trait for Circle {
    const PI:f32 = 3.14;
}

fn const_via_associated_constants<T: Trait>(_v: T) -> f32 {
    T::PI * 2.0
}

fn const_via_method <T: Trait>(v: T) -> f32 {
    v.double() * 2.0
}

fn main () {
    // use direct
    debug_assert!(Struct::PI == 3.14);
    debug_assert!(Circle::PI == 3.14);

    // use direct via method.
    debug_assert!(Struct{}.double() == 6.28);

    // use from a function(direct and via method)
    debug_assert!(const_via_associated_constants(Circle{}) == 6.28);
    debug_assert!(const_via_method(Circle{}) == 6.28);

    println!("Rust 1.20");
}

参考

Announcing Rust 1.20