Home  >  Article  >  Backend Development  >  How does Go Achieve Polymorphism without Inheritance?

How does Go Achieve Polymorphism without Inheritance?

DDD
DDDOriginal
2024-11-06 06:45:02173browse

How does Go Achieve Polymorphism without Inheritance?

Polymorphism in Go lang

As you have discovered, Go does not support the traditional object-oriented concept of polymorphism through inheritance. However, there are other ways to achieve similar results using interfaces and composition.

Interface and Composition

In Go, interfaces define contracts that specify the methods a type must implement. Composition allows you to create new types by embedding other types. By combining interfaces and composition, you can achieve a form of polymorphism.

For example, consider the following code:

<code class="go">package main

import "fmt"

type Foo interface {
    printFoo()
}

type FooImpl struct {
}

type Bar struct {
    FooImpl
}

type Bar2 struct {
    FooImpl
}

func (f FooImpl) printFoo() {
    fmt.Println("Print Foo Impl")
}

func getFoo() Foo {
    return Bar{}
}

func main() {
    fmt.Println("Hello, playground")
    b := getFoo()
    b.printFoo()
}</code>

In this example:

  • Foo interface defines a printFoo method.
  • FooImpl implements the Foo interface with a printFoo method.
  • Bar embeds FooImpl and therefore implements the Foo interface.
  • Bar2 embeds FooImpl and also implements the Foo interface.
  • getFoo returns a value of type Foo. Since both Bar and Bar2 implement the Foo interface, Bar2 is a valid return value for getFoo.
  • main calls getFoo to obtain a Foo value and then calls the printFoo method on that value.

When you run this code, you will see the following output:

Hello, playground
Print Foo Impl

This demonstrates how interfaces and composition can be used to achieve a form of polymorphism in Go. By defining an interface, you can ensure that different types share a common set of methods. By embedding types, you can create new types that combine the capabilities of multiple other types. This allows you to write code that treats different types in a uniform way.

The above is the detailed content of How does Go Achieve Polymorphism without Inheritance?. 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