1

Rust, unlike C++, does not have function overloading. Consider a linked list model that, in C++, would look like:

template <typename T>
class Node {
private:
    T value;
    std::unique_ptr<Node<T>> next;

public:
    Node<T>& getNext();
    const Node<T>& getNext() const;
};

When you deal with a constant list, you cannot modify it because you can only have access to const Node<T>&, at the same time you can modify a non constant list.

What is the equivalent of this behaviour in Rust? Consider a more complex example with multiple methods. Only some of them must be overloaded with both &mut self and &self.

pub struct Node<T> {
    value: T,
    next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
    pub fn getNext(&self) -> Option<&Self> {}
    pub fn getNext(&mut self) -> Option<&mut Self> {}
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
barsdeveloper
  • 930
  • 8
  • 28
  • Idiomatic Rust uses `snake_case`, not `camelCase`. – Shepmaster Jan 12 '18 at 14:58
  • also C++ is snake_case, just for information completeness (and types are lower case). – barsdeveloper Jan 12 '18 at 15:17
  • 2
    [gnzlbg's answer](https://stackoverflow.com/a/42514762/3650362) on the other question solves your problem directly. But I'd recommend against it. The ability to dispatch methods on the const-ness of the reference was one of my first big WTF moments learning C++ – trent Jan 12 '18 at 15:22
  • @barsan-md That's incorrect. There is no single style guideline for `C++`. – WBuck Aug 10 '20 at 14:22

0 Answers0