Hacker News new | ask | show | jobs
by zogrodea 925 days ago
I think the person you're replying to tried to address that point that classes are primarily a way to organise code when other possibly equally good or better options exist like modules. An F# module might (for example) look like below.

module Hello = let say() = "hi" // returns the string "hi"

There are mechanisms to encapsulate implementation details (private functions), to have multiple modules for different "domains" and specifying public contracts.

A class seems to imply more than that: each class specifies how to create an object with a constructor (where an object is something with the class's methods except modifying some state only owned by and accessible by the object itself).

1 comments

But in Rust you've got constructors as well. The only thing that really seems to be missing is inheritance. But I understand that one might say that classes without the possibility of using inheritance don't look fully right.
Rust does not have constructors.
I would call this [0] a constructor, why wouldn't you?

[0] https://doc.rust-lang.org/nomicon/constructors.html

Wikipedia defines it as

> a constructor is a special type of function called to create an object.

Now, I don't think Wikipedia is always the authority on everything, but this is how I view them as well. A constructor is kinda like a callback that the language runtime invokes when an something is created. For example, in C++:

  class Foo {
   public:
    Foo() {
      // your code goes here
    }
  };

  int main() {
    Foo a; // constructor invoked here
  }
(please excuse formatting, there is no unified C++ style so I just picked one)

or in Ruby:

  class Foo
    def initialize
      # your code goes here
    end
  end

  Foo.new # constructor invoked here
These "constructors" in Rust don't work like that at all. They are not special member functions that are invoked when something is created; they are the syntax to create something.
I think this is where things get muddy. On one hand, I think that there is still a function call going on under the hood, even if the syntax hides that. On the other, if you need some preprocessing before assigning the values to your struct's fields, you can still define a special member function that does whatever you need to figure out what the correct values are. In my view, what Rust is actually missing is the default constructor, because it will not initialize variables to some default value for you.
If you define a function that does some preprocessing before creating an instance in Rust, it is not a special member function that the language understands. It’s just a regular old function that happens to return an instance.

I do agree that it can be useful when discussing code to refer to these style functions with a more specific term, like a constructor, but that’s a colloquialism, and when discussing language features, being precise is important.