Home  >  Article  >  Backend Development  >  How to rewrite function in golang?

How to rewrite function in golang?

王林
王林Original
2024-04-27 11:15:02462browse

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.

如何在 golang 中重写函数?

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:

  • The overridden method must have the same signature as the overridden base method.
  • The receiver type of the overridden method must be a subtype of the base type.
  • There are no virtual methods or dynamic bindings in Go.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn