Skip to content

Allow struct method extensions #1170

@lerno

Description

@lerno

I would like to suggest that struct methods could be defined outside of the struct and even in different source files.

For example, assume we have a Vec3 struct, defined like this:

const Vec3 = struct {
   x: f32,
   y: f32,
   z: f32,

   pub fn init(x: f32, y: f32, z: f32) Vec3 {
     return Vec3 {
        .x = x,
        .y = y,
        .z = z,
     };
  }

  pub fn dot(self: *const Vec3, other: *const Vec3) f32 {
    return self.x * other.x + self.y * other.y + self.z * other.z;
  }
};

The proposal is that one could define extensions in other files like this:

pub fn Vec3.cross(self: *const Vec3, other: *const Vec3) f32 { ... }

One would obviously need to discuss how (if) this should be supported for generic structs.

This is not UFCS ( discussed in #148 ), but much more narrow change that might be a better fit for Zig.

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions