Hacker News new | past | comments | ask | show | jobs | submit login

And a more idiomatic example:

  struct X {
    X(Y val) : y_{val} {}

    // Can be called on const and non-const X objects
    const Y& y() const { return y_; }

    // Can only be called on non-const X objects
    Y& y() { return y_; }

  private:
    Y y_;
  };

  void f(X& x) { x.y() = 222; }
  void g(const X& x) { x.y() = 222); }

  const X x{123};  // x.y() == 123
  x.y() = 222; // compilation error
  f(x); // compilation error (f's parm is non-const)
  g(x); // compilation error (can't assign to const ref)

  // Cannot take non-const ref or ptr of x
  X& xr{x};  // compilation error
  X* xp{&x}; // compilation error
If the original declaration of the variable is const nothing can modify it. (And as my first example shows, the original declaration can always be const if you want it to be, regardless of context.) You can't take a non-const pointer or reference to x without explicitly circumventing the language like this:

  X& xr{const_cast<X&>(x)};
  X* xp(const_cast<X*>(&x)};



Sure, if the object was declared const in the first place, then it (mostly) can't be mutated. But the real power of const comes from const references, which in Rust guarantee that the referenced object will not be mutated while the reference is alive, even though it might have been mutated before.


I see. That's a nice feature.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: