Home > Backend Development > Golang > How Does Go Implement Polymorphism Without Enforcing It?

How Does Go Implement Polymorphism Without Enforcing It?

Mary-Kate Olsen
Release: 2024-11-06 02:29:02
Original
425 people have browsed it

How Does Go Implement Polymorphism Without Enforcing It?

Polymorphism in Go

In object-oriented programming, polymorphism allows a single interface to refer to objects of multiple types. Go does not strictly enforce this concept, but it offers alternative ways to achieve similar behavior.

Consider the following code snippet:

type Foo struct {
   ...
}

type Bar struct {
   Foo
   ...
}

func getFoo() Foo {
   return Bar{...}
}
Copy after login

As you noticed, in Go, this code raises an error indicating that getFoo() must return an instance of Foo. To achieve a polymorphic behavior, you can utilize interfaces and composition in 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()
}
Copy after login

In this updated example:

  • We define an interface called Foo that declares a function printFoo.
  • FooImpl implements the Foo interface.
  • Bar and Bar2 are structs that embed the FooImpl type.
  • The getFoo() function returns a value that implements the Foo interface, allowing it to return either a Bar or Bar2 instance.
  • When calling printFoo on the returned value from getFoo(), Go dynamically dispatches the method based on the underlying type.

This technique provides a way to achieve polymorphism in Go by utilizing interfaces and composition, allowing for a single interface to be used for different concrete types.

The above is the detailed content of How Does Go Implement Polymorphism Without Enforcing It?. 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