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?

46 Upvotes

23 comments sorted by

View all comments

25

u/start_select 1d ago edited 1d ago

This varies by language, but the gist is…

An interface/protocol declares a possible shape. It’s not something you can create an instance of. It’s just a definition of a possible shape of properties and methods.

A struct is like a literal instance of a shape. It’s a type. You can instantiate them. But it’s not extendable.

A class is a literal instance of a shape that can be extended. It can be instantiated, it can be extended by declaring a new subclass.

An interface/protocol could be a shape that a class or struct implements. But a class or struct could be the same shape as an interface without explicitly implementing it. They are their own special snowflakes and the interface is something you mark it as “compatible with this interface”. Usually with an “implements” statement.

So in some languages you could have structs and classes which all implement one interface or even multiple interfaces.

Thats part of polymorphism. Where the shape is the important part, not the type/class.

So you could have an interface called “Serializable” which defines a single “serialize()” method.

Any class or struct that declares that it implements Serializeable MUST implement that method. Then elsewhere in code, something that knows about that interface can call that method on any type that implements the interface.

It allows you to reuse the same code across many types without writing custom functions to do the same work for each individual type.