Skip to content

const candidate

Don Isaac edited this page Nov 16, 2024 · 5 revisions

Proposed Rule: const-candidate

  • suggested by: @DonIsaac
  • category: suspicious
  • enabled by default: yes

Summary

Warn when a *Foo pointer is only ever used as *const Foo.

Details

When a function takes a *Foo as a parameter, it indicates that the pointed-to value may be mutated. If that pointer is only ever used after being cast to a const pointer, then the parameter should also be const.

Example

const std = @import("std");

const Foo = struct {
    i: u32,
    fn print(self: *const Foo) void {
        std.debug.print("This foo's .i field is {d}\n", .{self.i});
    }
};

// foo param should be *const Foo
fn doThingWithFoo(foo: *Foo) void {
    foo.print();
}

pub fn main() void {
    var foo: Foo = .{};
    doThingWithFoo(&foo);
}

Notes

I'd like this to also work with struct field properties, but this may be more difficult. This is particularly true since no container field can be private. For pub structs, this would require cross-file analysis.

Clone this wiki locally