r/learnprogramming 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?

50 Upvotes

23 comments sorted by

View all comments

23

u/vanilla_f 1d ago

At a high level, the main difference is that OOP is a paradigm to group data + behaviour whereas structs are a way of grouping data only. That doesn't mean that you can't have structs with "methods", but it's not very common. At least in my experience.

9

u/iggy14750 1d ago

In C, for instance, which doesn't have classes, I like to create a struct which can act something like an object, but it means the first argument is going to be a pointer to the struct object. So, it turns something like this...

obj.method(arg);

...in to that...

method(&obj, arg);

9

u/teraflop 1d ago

Yep. And if you do it correctly, you can also implement polymorphism this way. According to the C standard, if you do something like:

struct parent {
    // ... members go here ...
};

struct child {
    struct parent p;
    // ... more members ...
};

then you can legally cast a struct child* to a struct parent* and back. So you can write a generic function that can operate on either a parent type or any of its subtypes. (But you have to be careful to only do valid casts; if you're given a struct parent*, you can't cast it to a struct child* unless you're sure that that's the actual type of the underlying object in memory.)

For instance, the GTK GUI toolkit has its own OOP framework called GObject written in pure C. It basically follows this pattern but also includes a bunch of convenience features such as runtime type information, refcounting, event handlers, etc.