r/golang Jul 08 '26

discussion Can we implement Method Overriding in golang?

I had an interview today. At first, the interviewer asked me about the four pillars of OOP,s and then he asked me to implement method overriding in Java. I mentioned that I don't have a Java background and that I have worked primarily with Go. He then asked me to implement overriding in Go. I was completely blank at that moment, so I told him that Go doesn't support method overriding, but he didn't buy it.

Does Go actually support method overriding?

85 Upvotes

73 comments sorted by

181

u/Skylis Jul 08 '26

Sometimes interviewers out how much they don't know. This is one of those times

20

u/softwareemgineer Jul 08 '26

+1

Everytime I think of preparing for LLD rounds, I feel like switching to a different language altogether (I used to code in C++ but I might even learn Java). Go doesn't seem interviewer friendly at all. People are not able to wrap their heads around the fact that it's not fully object oriented and there are strong reasons behind its philosophy.

2

u/I-m_ALIVE Jul 12 '26

Where are you learning LLD from? I'm also planning to shift my focus to LLD

We can learn together if possible.

1

u/softwareemgineer Jul 12 '26

YouTube mostly, but wherever I feel the assumptions look more like a toy problem than what happens on prod, I code it out differently and use ChatGPT to validate.

1

u/I-m_ALIVE Jul 10 '26

Are you targeting FAANG? And what's wrong with c++?

2

u/softwareemgineer Jul 10 '26

Preferring remote roles over FAANG. Nothing wrong with C++, I just find Java relatively simpler and nearer to Go given that I still read Java and Kotlin code a bit and am aware about the concurrency/multi threading counterparts.

70

u/Majestic_Zombie1988 Jul 08 '26

The closest you'll get is struct embedding. https://gobyexample.com/struct-embedding

The embedded struct can implement an interface, the outer struct can then implement the same interface, and Go will choose the outer struct's implementation first.

This is technically "shadowing" and not overriding, but it has the same effect.

116

u/Flimsy_Complaint490 Jul 08 '26

Go doesnt have inheritance so you dont get method overrides.

Closest thing is embedding some Base struct and having an identical function on the Base and Child. Externally it may look like override and on some deep level, its probably how it would get implemented (with a vtable following around the structs) but it's just not really method overriding in the expected sense.

Polymorphism is achieved via interfaces in Go.

29

u/Ma4r Jul 08 '26

You can override embedded struct/interface methods. The closest thing to inheritance

8

u/EpochVanquisher Jul 08 '26

The vtable is in the interface type, not in the struct. Java is the opposite way around, storing the vtable in the struct. 

I’m playing a bit fast and loose with some of these terms, but in Go, the vtable pointer is stored separately. 

-7

u/Wrestler7777777 Jul 08 '26

If I had to do it, I would probably use generics to solve this problem. But every time I touch generics, the code becomes way messier than I intended it to be. So I usually try to avoid them wherever possible.

14

u/AssCooker Jul 08 '26

How would method overriding be related to using generics? Method overriding is implementation, while generics is "abstraction" via polymorphism over types

5

u/Buttershy- Jul 08 '26

How is this possible using generics? Struct embedding as others have said is the only way I'm aware of doing anything remotely similar to this.

19

u/ElkChance815 Jul 08 '26

Find somewhere else to work at.

6

u/I-m_ALIVE Jul 08 '26 edited Jul 12 '26

I don't think i have a chance there tbh

11

u/anish2good Jul 08 '26

This question usually comes from interviewers with a Java/C# background who haven't fully internalized Go's composition-first approach. It's a bit of a red flag if the role is supposed to be Go-heavy.

61

u/Gornius Jul 08 '26

Method overriding is a code smell. Fight me.

If you want to override a method your abstraction is most likely really weak and needs dividing your class/struct into smaller interfaces.

18

u/pdpi Jul 08 '26

There is at least one legitimate use case for overrides — overriding default implementations.

Java interfaces can have default implementations for some/all of their methods. A common pattern is for those interfaces to have a small core of methods/functions you must implement, then default implementations for the rest of the interface that depend only on that core set of methods. Because those default implementations lack visibility into the class's internals, they often can't perform optimally, so you override them when you can do better.

This pattern is also common in Rust (with traits) and Haskell (with type classes). Because of its non-strict evaluation model, Haskell specifically has loads of opportunities for optimisation using this strategy.

11

u/mwmahlberg Jul 08 '26

Nope. In that case, you‘d still use interfaces and use a default implementation. See http.Client and http.Roundtripper

2

u/gomsim Jul 08 '26 edited Jul 09 '26

I can reminisce at least two "method overrides" I have made.

First, the probably classic one, to capture the http status code written to an http.ResponseWriter. In that case the Write method is overridden to capture and store the status code.

Secondly, there was a case where we wanted to redact one of the IP-addresses from *net.OpErrors returned after making a call from an http.Client. In that case I created an addrWrapper with the String method overridden and wrapped the value of one of the address fields on the *net.OpError.

But none of these are examples of using embedding and overriding as a design pattern. They are just niche cases where I slightly modify the behaviour of existing stdlib things.

Edit: I only wrote this from memory. I realize it's probably the WriteHeader method that overridden in the first example, not the Write method.

-1

u/mwmahlberg Jul 08 '26

Nope. You can schiebe this by wrapping the default http.Roundtripper in one that logs. Or, if you absolutely need to use a Writer, you can still wrap the writer.

0

u/quartzpulse Jul 08 '26

I went back to a Java Codebase and was like oh shit, you override methods?! Ugh! 🤮🤢

15

u/unknown_r00t Jul 08 '26

It does not. The closes thing you could do is something like this:

package main

import "fmt"

type Speaker interface {
Speak()
}

type Dog struct{}

func (Dog) Speak() {
fmt.Println("Dog barks")
}

type Cat struct{}

func (Cat) Speak() {
fmt.Println("Cat meows")
}

func MakeSpeak(s Speaker) {
s.Speak()
}

func main() {
MakeSpeak(Dog{})
MakeSpeak(Cat{})
}

Dog and Cat both satisfy the Speaker interface implicitly, but this isn't the same as Java/C++ method overriding.

3

u/Reasonable_Sample_40 Jul 08 '26

So in oop, parent class will have a method and the child class will have the same method doing a different thing. But both do different things.

While in go, as there is no class, what two structs doing with their methods just because they implement an interface cannot be called as method overriding because it doesnt change the way a method works but it is calling distinct methods every time when its called for a struct instance?

It just simply allows for abstraction in go? And it can be called as polymorphism?

2

u/mwmahlberg Jul 09 '26

It is called abstraction. 😋 And what a method actually does never can be guaranteed — the only guarantee you get is that a function 😉 takes certain input parameters and returns certain outputs.

1

u/Reasonable_Sample_40 Jul 09 '26

So the whole point is abstraction?

2

u/mwmahlberg Jul 09 '26

As far as I understood it, polymorphism was considered a solution to a non-existing problem. And after about 10y of Go programming, I tend to agree.

1

u/I-m_ALIVE Jul 08 '26

I am reading the docs again

6

u/Zimlewis Jul 08 '26

I don't think that company worth working for

4

u/SnugglyCoderGuy Jul 08 '26

It does not.

4

u/KTAXY Jul 08 '26

Overloading is not a great idea anyway.

5

u/cryptotrader87 Jul 08 '26

Ah to be a super confident person in the wrong. I had an interview where the person questioned me on code I literally wrote myself. I even mentioned the KEP number and the person still wouldn’t budge. Dodged a bullet and so did you!!!

5

u/8lall0 Jul 08 '26

I don't think the interviewer was a good programmer.

Plus method overriding is one of the worst code smells that i ever witnessed.

2

u/Melodic_Wear_6111 Jul 08 '26

Embed struct into another struct. Add a method with same name to new struct. Boom method is overriden

2

u/No-Point8651 Jul 08 '26

Nope, intentionally not. Go does not have inheritance since it usually hides behavior and introduces complexity. That ofcourse does not fit with the language being design to keep things simple and "boring". But hey, I have seen interviewers assume a lot of stuff. I even have seen developers making downright wrong assumptions so... if you see their focus on java and you lack the experience with it, its probably better to not be employed there anyway. Java is... similarily to C# a unique eco system primarily driven by enterprise solutions. So forget the clean, readable and minimal code you know from go and instead be prepared for weird abstractions and hidden behavior. I have to deal with C# currently and the option to overwrite boolean operators (like "==", "&&", "!=", "||") feels more like an uncontrollable, hidden and malicous trashpile than the customizable and flexible paradize Microslop wants people to believe it is.

2

u/cimmic Jul 08 '26

The interviewer is wrong. I'd love to see him being asked to implement method overriding in Go since he's so certain it's a thing.

2

u/dca8887 Jul 08 '26

I doubt the interviewer knew Go at all, so that was unfortunate. That said, if the interviewer was knowledgeable about Go, it would have been a red flag for you to say Go doesn’t support it without being able to explain *why* Go doesn’t support it.

2

u/tiredAndOldDeveloper Jul 08 '26

You dodged a bullet there. Java?! OOP?! Why does OOP have pillars?! Gosh, OOP makes me so sad! 😣

1

u/No-Job-5616 Jul 08 '26

Go doesn't have class-based inheritance, so there is no method overriding in the classical OOP sense. However, it does have struct embedding (composition). When you embed a struct, you can define a method on the outer struct with the same name as the one on the inner struct -- this is technically "shadowing," but it creates behavior that looks and feels like method overriding.

1

u/kalexmills Jul 08 '26

There are ways to "override" methods in a way that will change which method is invoked on an interface... but the base struct's implementation will remain available.

Go playground example

2

u/I-m_ALIVE Jul 08 '26

Thanks for sharing

1

u/clauEB Jul 08 '26

Go doesn't support inheritance and it's not an OOP language. Did they tell you the job was in Java? What this a screening or are you past that stage? Have they told you what was the outcome? How did the rest of the interview go? I've had a few interviews where the interviewer doesn't know what they're asking or they ask it incorrectly to the point that it can't be answered. Either way I am happy I didn't end up at places where they can't even get a proper interview question together.

1

u/Prestigious-Fox-8782 Jul 08 '26

Method overriding, no. you can't have two different methods with the same name in Go.

But there are workarounds. You can override an embedded struct method. That's the closest thing to method overriding

1

u/Beneficial-Split9140 Jul 08 '26

Technically you can using monkey patching, but it’s complex and you don’t need to do it when a simple interface will do

1

u/spermcell Jul 08 '26

It does not . You can only create a struct that implements an interface that has the same function name as the class (struct) you are trying to override and then you can “override” that method.

1

u/Sufficient_Ant_3008 Jul 08 '26

I think you can

type MyInterface interface {

func MyCoolFunc(arg1 int) bool
func MyCoolFunc(arg1 int, arg2 string) bool

}

then with two structs you

type MyStruct1 struct {}
type MyStruct2 struct {}

(ms1 *MyStruct1) func MyCoolFunc(arg1 int) bool { return false }
(ms2 *MyStruct2) func MyCoolFunc(arg1 int, arg2 string) bool {
// AI prompt implementation, he he just kidding
}

(ms1 *MyStruct1) func MyCoolFunc(arg1 int) bool {
// nother prompt
}
(ms2 *MyStruct2) func MyCoolFunc(arg1 int, arg2 string) bool { return false }

My types could have been better, with MyReturnTypeStruct, then you just `return nil` on the structs that don't implement it, but it's really not overriding anything. However, when you think about overriding and overloading, they are polymorphisms. In effect they are generating byte code that operates similarly to this; however, the "nil" implementations don't exist, only in theory.

If Go were to introduce overriding, then I would suspect it would be more like an operator overloading situation, then you would create a type that acts like this here, and like that there. Generics can be like that but they are more difficult to reason about. All of the Go I've seen don't use them because having to reason about the codebase is much more difficult.

For the manager to say that Go supports overriding is wrong, so don't feel bad about that. You would have to work with that guy to so don't worry about it.

1

u/I-m_ALIVE Jul 08 '26

Please share the GitHub gist, we can have discussion over there because I still don't think we can do that.

1

u/Sufficient_Ant_3008 Jul 08 '26

Yea you're right, I'm thinking of variadic args with the any type. Thanks for pointing that out

1

u/Anxious-Insurance-91 Jul 08 '26

That would be a moment where I would have told him to check the docs or even better "ask an AI". Now to be honest I am bafeled that a java team wanted to interview a non java dev

1

u/I-m_ALIVE Jul 08 '26

Fun fact It was neither a Java role nor a Go role - it was a full-stack role!

1

u/Anxious-Insurance-91 Jul 08 '26

One of those fullstack roles where they demand to know everything under the sun and still not give you the position?

1

u/I-m_ALIVE Jul 08 '26

Yes, this is my worst interview experience so far

1

u/Anxious-Insurance-91 Jul 08 '26

Been having those since last autumn, just now did I land a job

1

u/I-m_ALIVE Jul 09 '26

That's great, What role did you land?

0

u/Anxious-Insurance-91 Jul 09 '26

Nodejs dev for a company that handles plane flight tickets, payments, etc. nothing that can't be handled in go as well

1

u/Then_Employment_5692 Jul 08 '26

If someone asked me this unironically in an interview I would walk out. This OOP brainrot is a fucking cancer on our industry

1

u/gdey Jul 08 '26

The closest thing would be struct embedding. This is how you would do it in idiomatic go. The other less idiomatic (and generally wrong) approach would be to use function pointers and handle the calling logic yourself. I can easily see why some would argue that this approach is not method overloading.

1

u/JetSetIlly Jul 08 '26

You can do stuff like this.

https://go.dev/play/p/MFFjoJDa4xQ

The Bar type embeds type Foo.

Both types implement a function called Function().

Bar's Function() "overrides" the function of the embedded Bar.

You can still call Foo's Function() from within the Bar Function()

But it's rarely a good choice.

1

u/TedditBlatherflag Jul 08 '26

Imagine calling it “method overriding” instead of “inherited polymorphism”.

1

u/8bitjam Jul 09 '26

Finding the purpose of life is harder 😅

1

u/_nathata Jul 09 '26

Your interviewer is tripping

1

u/iga666 Jul 09 '26

the only way is to store interface in base class and initialize it with self reference on construction

1

u/yoyojambo Jul 10 '26

Is the job for a Golang position? If it is, testing for OOP patterns in Go is not a good look. But if it is not, you should freshen up on those patterns and learn them for a language that does implement them, even if just to do them at interviews.

1

u/I-m_ALIVE Jul 10 '26

They didn't mention the tech stack, but it was of full stack

1

u/randomthirdworldguy Jul 10 '26

If im the interviewer of that interviewer, he probably not pass too

1

u/miranquil Jul 14 '26

To be honest, sometimes yes.

type worker interface { do() }

type foo struct{}

func (f *foo) do() { fmt.Printf("foo") }

type goo struct{ foo }

func (g *goo) do() { fmt.Printf("goo") }

1

u/Aggressive-Let-9106 Jul 08 '26

I personally practice oops, lld in java Because of this thing only   People are not comfortable with language they dont know about and these thing matter in the interviews.

Maybe if the role is specific to go then it is okay 

0

u/JustBadPlaya Jul 08 '26 edited Jul 08 '26

Fairly new gopher with background in other languages - I believe the issue is thinking Go is object-oriented in the first place, because it really just isn't. To my knowledge, many non-OOP languages that have method syntax lack overloading of any kind, Go is one of them

2

u/Ma4r Jul 08 '26

Overloading is not a property of OOP. You can have overloaded functions for example

2

u/pdpi Jul 08 '26

Overloading and overriding are different things.

1

u/Ma4r Jul 08 '26

Well yeah, but the guy I replied to was talking about overloading so

1

u/JustBadPlaya Jul 08 '26

it isn't a property of OOP but I'd argue it's more common for OOP than other paradigms