Skip to content

const fn in Trait implementation. #71971

Description

@ldm0

For code like this:

#[derive(Debug, Clone, Copy)]
pub struct Vec3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl std::ops::Add<Vec3> for Vec3 {
    type Output = Vec3;
    const fn add(self, b: Vec3) -> Self::Output {
        Vec3 {
            x: self.x + b.x,
            y: self.y + b.y,
            z: self.z + b.z,
        }
    }
}

This currently emits:

error[E0379]: functions in traits cannot be declared const                                                                                                                                                  
  --> src\main.rs:10:5
   |
10 |     const fn add(self, b: Vec3) -> Self::Output {
   |     ^^^^^ functions in traits cannot be const

error: aborting due to previous error                                                                                                                                                                       

For more information about this error, try `rustc --explain E0379`.

It would be extremely useful if we could have const fn in trait implementation (especially for operator overloading). And I saw this is also mentioned in the RFC 0911.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)F-const_trait_impl`#![feature(const_trait_impl)]`

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions