Skip to content

Generalizing over pointer type #52288

@axos88

Description

@axos88

My use case is a bit more complex than this, but I'm trying to simplify the issue with this abstract example:
Say I have a structure

  struct Foo {
    bar: u32,
    baz: u32,
    ....
  }

How can I write a get_bar function which can generalize over the mutability of the self parameter?
Pseudocode:

  impl Foo {
    fn<?PT> getBar(&PT self) -> &PT u32 where PT = {mut immut} {
       &PT self.bar
    }

If called with a mutable pointer, it would return a mutble pointer to the inner field, if called with an immutable, it would return an immutable.

My goal is to avoid having to define a nonmut and a mut version of each function, by copy pasting code basically:

  impl Foo {
    fn get_bar(&self) -> &u32 { &self.bar }
    fn get_bar_mut(&mut self) -> &mut u32 { &mut self.bar }
  }

If the body of the function is more complex than this (my case is a recursive function), it gets pretty nasty, and there is a lot of code that is being copy&pasted, something that should be avoided.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions