CodeBlanks Logo Icon CodeBlanks

Associated constant

Define an associated constant.

Associated constants

Traits can declare constants too; each implementation gives its own value. The values are known at compile time and accessed through the type:

trait Cokgen {
    const KENAR: u32;
    const AD: &'static str;
}

struct Ucgen;
impl Cokgen for Ucgen {
    const KENAR: u32 = 3;
    const AD: &'static str = "üçgen";
}

fn ozet<T: Cokgen>() -> String {
    format!("{}: {} kenar", T::AD, T::KENAR)
}

A constant can have a default value too: const AZAMI: usize = 64;.

Usage examples

In the standard library: u32::MAX, f64::EPSILON, char::MAX. In your own code: unit conversions, protocol versions, buffer sizes. Associated constants can also be used as array sizes together with const generics:

struct Kare;
impl Cokgen for Kare {
    const KENAR: u32 = 4;
    const AD: &'static str = "kare";
}

println!("{}", ozet::<Kare>());   // kare: 4 kenar

Practice Polygon constants

Implement the Cokgen trait above for Ucgen and Kare and write the ozet function. Print the results of ozet::<Ucgen>() and ozet::<Kare>() on separate lines.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
trait Cokgen {
    const KENAR: u32;
    const AD: &'static str;
}

struct Ucgen;
struct Kare;

impl Cokgen for Ucgen {
    const KENAR: u32 = 3;
    const AD: &'static str = "üçgen";
}

impl Cokgen for Kare {
    const KENAR: u32 = 4;
    const AD: &'static str = "kare";
}

fn ozet<T: Cokgen>() -> String {
    format!("{}: {} kenar", T::AD, T::KENAR)
}

fn main() {
    println!("{}", ozet::<Ucgen>());
    println!("{}", ozet::<Kare>());
}

Expected output

üçgen: 3 kenar
kare: 4 kenar

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why can associated constants be used without <code>self</code>?

  • It can't be
  • Because it's global
  • The value belongs to the type, not to an instance Correct answer
  • It's a static variable

Explanation: T::KENAR is substituted at compile time; there's no runtime cost.

2 Constant declaration

Question
trait Cokgen {
    ____ KENAR: u32;
}
Answer
trait Cokgen {
    const KENAR: u32;
}

Explanation: Constants in a trait are declared with const.

3 Constant and value

Term Meaning
Ucgen::KENAR 3
Kare::KENAR 4
u8::MAX 255
i8::MIN -128

All lessons in Advanced