How to return const from trait function

Hi, how do I return const from trait func? using generic constant? Thanks


pub trait Getter<T> {
	fn get() -> T;
}

struct My;
impl Getter<u8> for My {
	fn get() -> u8 {
		7
	}
}

const CONST: u8 = My::get();

#![feature(const_trait_impl, effects)]

#[const_trait]
pub trait Getter<T> {
	fn get() -> T;
}

struct My;
impl const Getter<u8> for My {
	fn get() -> u8 {
		7
	}
}

const CONST: u8 = My::get();

Rust Playground

4 Likes

Unfortunately, const fn in trait is not supported, so there's no real way to implement this (yet) in stable Rust. The heart of the problem is the still-in-preparation implementation of const-polymorphism.

Calling methods on generic parameters of const fns by oli-obk ยท Pull Request #2632 ยท rust-lang/rfcs ยท GitHub may be of interest to you.

In your use case, you might be able to handle a workaround like this:

pub trait Getter<T> {
    const VALUE: T;
}

struct My;
impl Getter<u8> for My {
    const VALUE: u8 = 7;
}

const CONST: u8 = My::VALUE;
1 Like

Hi @vague thanks for the reply, if I need the impl to work for both Const and non-const, is it possible?

โ€˜โ€™โ€™
const CONST : u8 = My::get();

let NON_CONST : u8 = My::get();

assert_eq!(My::get(), 7);

โ€˜โ€™โ€™

Yes, const functions can be called in both const and non-const contexts.

3 Likes