Home > Backend Development > Golang > Why Doesn't a Go Function Returning a Struct Pointer Automatically Implement an Interface?

Why Doesn't a Go Function Returning a Struct Pointer Automatically Implement an Interface?

Linda Hamilton
Release: 2024-12-20 13:13:13
Original
290 people have browsed it

Why Doesn't a Go Function Returning a Struct Pointer Automatically Implement an Interface?

Interface Implementation in Go: Function Types Returning Structs

When working with Go, it is common to encounter situations where a function returns a struct that implements an interface. However, you may face an error similar to "cannot use [function] as type [interface] in field value" when attempting to assign the function to a field that expects an instance of the interface.

To understand this error, it is crucial to clarify that a function that returns a pointer to a struct (struct) does not automatically implement an interface defined for that struct. In other words, struct and struct are distinct types in Go.

In the given example, the function getInstance is expected to return a value of type myInterface, which is a description of behavior (interface) rather than a specific implementation (struct). However, getInstance returns a pointer to the myStruct implementation (*myStruct), which is not type-compatible with myInterface.

To resolve this issue, you need to modify getInstance to return an instance of the myStruct struct, as seen in the corrected code below:

package main

import "fmt"

func main() {
    var function func() myInterface

    function = getInstance

    newSomething := function()

    newSomething.doSomething()
}

type myInterface interface {
    doSomething()
}

type myStruct struct{}

func (m *myStruct) doSomething() {
    fmt.Println("doing something")
}

func getInstance() myInterface {
    return &myStruct{}
}
Copy after login

This modification ensures that myStruct implements the myInterface interface, and the getInstance function returns the correct type.

While the above approach works, Go has proposed a language change to automatically convert a function returning a concrete type to a function returning an interface if the concrete type implements the interface. However, this proposal was rejected due to potential performance and safety concerns.

The above is the detailed content of Why Doesn't a Go Function Returning a Struct Pointer Automatically Implement an Interface?. 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