RFC 0195 - Associated Items and const fn

RFC 0195 - Associated Items, dated 2014-08-14, lists the following items:

  • Associated Functions (already present as “static” functions)
  • Associated consts
  • Associated types
  • Associated lifetimes

Suspiciously missing from this list is “Associated const fn”.

It was brought to my attention that RFC 0911 - const fn, dated 2015-02-25, was created more than a year after the Associated Items RFC, so it didn’t make the list.

I’m wondering if the language team would entertain an RFC that finishes filling out the Associated Items with const fn. Assuming “yes”, should this be a new RFC, or an amendment to the existing Associated Items RFC?

I’m suggesting an amendment to the existing RFC and a new issue to track its implementation.

4 Likes

Associated functions can already be constant (See the constructors for the atomic types).

Yes, cont fn can be used in impl struct, but not in traits.

This works fine:

#![feature(const_fn)]
#![feature(associated_consts)]

struct TestStruct{}

impl TestStruct {
    const fn get_some_number(&self) -> i32 {
        42
    }
}

fn main() {
    let test = TestStruct{};
    println!("{}", test.get_some_number());
}

Playground

This does not:

#![feature(const_fn)]
#![feature(associated_consts)]

struct TestStruct1{}

trait TestTrait {
    const fn get_some_number(&self) -> i32;
}

impl TestTrait for TestStruct1 {
    const fn get_some_number(&self) -> i32 {
        42
    }
}

struct TestStruct2{}

impl TestTrait for TestStruct2 {
    const fn get_some_number(&self) -> i32 {
        43
    }
}

fn main() {
    let test1 = TestStruct1{};
    let test2 = TestStruct2{};
    println!("{} {}", test1.get_some_number(), test2.get_some_number());
}

Playground

error[E0379]: trait fns cannot be declared const


EDIT:

Constants are more consistent:

This works:

#![feature(const_fn)]
#![feature(associated_consts)]

struct TestStruct{}

impl TestStruct {
    const SOME_NUMBER: i32 = 42;
}

fn main() {
    println!("{}", TestStruct::SOME_NUMBER);
}

Playground

And so does this:

#![feature(const_fn)]
#![feature(associated_consts)]

struct TestStruct1{}

trait TestTrait {
    const SOME_NUMBER: i32;
}

impl TestTrait for TestStruct1 {
    const SOME_NUMBER: i32 = 42;
}

struct TestStruct2{}

impl TestTrait for TestStruct2 {
    const SOME_NUMBER: i32 = 43;
}

fn main() {
    println!("{} {}", TestStruct1::SOME_NUMBER, TestStruct2::SOME_NUMBER);
}

Playground

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.