Home > Backend Development > Golang > How to Assign a Function Returning a Struct Implementing an Interface in Go?

How to Assign a Function Returning a Struct Implementing an Interface in Go?

Barbara Streisand
Release: 2024-12-06 20:28:13
Original
886 people have browsed it

How to Assign a Function Returning a Struct Implementing an Interface in Go?

Using Go Function Types that Return Structs with Interfaces

Question:

In Go, I have a struct in one package that implements an interface. In another dependent package, I want to create a fake implementation of this struct for testing purposes. However, Go is complaining about type safety when I try to assign a function returning a struct that implements the interface to a variable of that interface.

Architecture:

// Package expensive
type myStruct struct{}

func (m *myStruct) DoSomething() {...}
func (m *myStruct) DoSomethingElse() {...}
func CreateInstance() *myStruct {...} // Expensive to call

// Package main
type myInterface interface {
    DoSomething()
}

type structToConstruct struct {
    factoryFunction func() myInterface
}
func (s *structToConstruct) performAction() {...}
Copy after login

Error:

"cannot use expensive.CreateInstance (type func() *expensive.myStruct) as type func() myInterface in field value"

Answer:

The issue arises because the CreateInstance function returns a *myStruct value, which differs from the func() myInterface type required by factoryFunction. To resolve this:

// Package main
type myInterface interface {
    DoSomething()
}

type myStruct struct{}

func (m *myStruct) DoSomething() {...}

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

With this modification, getInstance now returns an myInterface type, allowing it to be assigned to factoryFunction.

Additional Notes:

  • Originally, the question involved a function type that returned a pointer to the struct rather than the struct itself, which caused the type mismatch.
  • To implement this behavior in the original code, a wrapper function can be used:
wrapper := func() myInterface {
    return expensive.CreateInstance()
}
Copy after login

The above is the detailed content of How to Assign a Function Returning a Struct Implementing an Interface in Go?. 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