In Go, method overriding allows methods in a base class to be redefined in a derived class while maintaining the same method signature: use the override keyword. The overridden method must have the same signature as the base method. The receiver type of the overridden method must be a subtype of the base type.
Overriding functions in Go
Overriding allows us to define new implementations of existing methods in derived classes while Preserve method signature. This allows us to extend the functionality of the base class without changing its interface.
Syntax
Overriding in Go uses the override
keyword:
type MyStruct struct { baseStruct } func (m MyStruct) SomeMethod() {}
SomeMethod
method Will override the method of the same name from baseStruct
.
Note:
Practical case
Suppose we have a Animal
base class with Speak
method:
type Animal struct { name string } func (a Animal) Speak() { fmt.Printf("%s speaks!\n", a.name) }
We can create a Dog
derived class that extends the Speak
method to bark:
type Dog struct { Animal } func (d Dog) Speak() { fmt.Printf("%s barks!\n", d.name) }
Here, Dog.Speak# The ## method overrides the
Animal.Speak method, providing a Dog-specific implementation.
Example
package main import "fmt" type Animal struct { name string } func (a Animal) Speak() { fmt.Printf("%s speaks!\n", a.name) } type Dog struct { Animal } func (d Dog) Speak() { fmt.Printf("%s barks!\n", d.name) } func main() { a := Animal{name: "Animal"} a.Speak() // Output: Animal speaks! d := Dog{Animal{name: "Dog"}} d.Speak() // Output: Dog barks! }
The above is the detailed content of How to rewrite function in golang?. For more information, please follow other related articles on the PHP Chinese website!