How Can Method Overriding Be Achieved in Go Using Interfaces?

Susan Sarandon
Release: 2024-11-13 03:56:02
Original
757 people have browsed it

How Can Method Overriding Be Achieved in Go Using Interfaces?

Method Overriding in Go with Interfaces

Unlike Java, where method overriding involves inheriting and modifying a base class's implementation, Go offers a solution using interfaces.

Interfaces define a set of method signatures that a type must implement. By creating an interface with a method that matches the desired behavior, you can implement it in a new type that can be used in place of the original one.

To achieve this, consider the following example:

type Base struct{}

func (base *Base) Get() string {
    return "base"
}

func (base *Base) GetName() string {
    return base.Get()
}
Copy after login

To implement method overriding, create an interface:

type Getter interface {
    Get() string
}
Copy after login

Modify the Base type to embed the Getter interface:

type Base struct {
    Getter
}
Copy after login

Now, create a new type that embeds Base and implements the Get method:

type Sub struct {
    Base
}

func (sub *Sub) Get() string {
    return "Sub"
}
Copy after login

Finally, modify the GetName method in Base to utilize the Getter interface:

func (base *Base) GetName() string {
    if g, ok := base.Getter.(Getter); ok {
        return g.Get()
    } else {
        return base.Get()
    }
}
Copy after login

This approach allows you to retain existing consumers of Base while providing the ability to override the Get method in subclasses.

Alternatively, you can also use the following method:

func New() *Sub {
    userType := &Sub{}
    userType.Getter = interface{}(userType).(Getter)
    return userType
}
Copy after login

In this case, you must manually set the Getter field in the user code to enable method overriding. Both methods achieve the desired result, but the first approach is considered more idiomatic in Go.

The above is the detailed content of How Can Method Overriding Be Achieved in Go Using Interfaces?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template