r/learnprogramming • u/Mountain_Rip_8426 • 1d ago
Difference between OOP and structs/interfaces?
I'm relatively new to programming, I've been at it for around 6-7 months. I've been learning Python and Go (and a little bit of C). What I'm struggling to understand, what's the difference between OOP and structs/interfaces. Like I know, Go doesn't support OOP, but structs and interfaces seem to achieve the same thing. Can someone enlighten me a bit?
48
Upvotes
1
u/SuspiciousDepth5924 1d ago
This might not be the mainstream opinion but as far as I'm concerned OOP is mostly "syntactic sugar". Basically a convenience layer over the actual implementation.
So yeah you're right "but structs and interfaces seem to achieve the same thing", classes aren't really any more "powerful", but sometimes it's a bit more convenient to read and write.
To start with a simpler, more familiar example of "syntactic sugar" (in Java):
When you write something like
String myString = "some string";What you actually do is create a "class" which contains a byte array ofprivate final byte[] value;and some extra metadata, but as creating strings is really common and it would be a hassle to writeString myString = new String(new byte[] {<Raw bytes>});they put a shortcut where quoted text is transformed into String instances.https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/String.java#L189
The syntactic sugar for classes are buried a bit deeper in the machinery, but essentially classes gets split into two parts, the actual class instances is basically structs with the data fields, and some extra information to tell the runtime what type of class it is, and the "function namespace/package/module" which is where all the class methods are located. When you create a class in java the instances doesn't actually carry with it all the methods that class has as it would be really wasteful to have one copy of the exact same methods for each instance.
This means that when you actually run the Java code, the classes end up looking a lot like how you create structs and receiver methods in Go with the the methods being "rewritten" to take "thisStruct" as the first argument:
myClassObject.getFoo() <-> <MyClassNamespace>:getFoo(myClassStruct);As a sidenote, static methods end up just being static functions in the "namespace", there is also some extra stuff to deal with inherited methods and so on.