Home > Backend Development > Golang > Why Doesn't My Go Struct Implement the Interface: Mismatched Method Parameters?

Why Doesn't My Go Struct Implement the Interface: Mismatched Method Parameters?

Barbara Streisand
Release: 2024-12-04 12:28:11
Original
539 people have browsed it

Why Doesn't My Go Struct Implement the Interface: Mismatched Method Parameters?

Interface Implementation Hindrance with Mismatched Method Parameters

Problem:

In a Go program, a structure's inability to implement an interface stems from a mismatch between the method parameter types in the structure and the interface.

Solution:

For a structure to implement an interface, its methods must precisely match the method signatures defined in the interface. This includes not only the method name and return type but also the parameter types.

In the provided code, the Connect method of the D structure takes an (*C) parameter instead of an (A) parameter, as required by the B interface it aims to implement. This mismatch causes the error.

To resolve the issue, the Connect method must be modified to match the interface's signature:

package main

import "fmt"

type A interface {
    Close()
}

type B interface {
    Connect() (A, error)
}

type C struct {
}

func (c *C) Close() { fmt.Println("Closing C") }

type D struct {
}

func (d *D) Connect() (A, error) {
    c := new(C)
    return c, nil
}

func test(b B) {
    c, _ := b.Connect()
    fmt.Println("Creating A from B")
    c.Close()
}

func main() {
    d := new(D)
    test(d)
}
Copy after login

With this correction, the D structure now implements the B interface:

func (d *D) Connect() (A, error) {
    c := new(C)
    return c, nil
}
Copy after login

Auxiliary Notes:

  • Interfaces foster code reusability by allowing different types to share common methods.
  • Implementing an interface guarantees that a type provides the necessary functionality defined in the interface.
  • It's essential to ensure that the parameter types in the method implementations match the interface's specifications.

The above is the detailed content of Why Doesn't My Go Struct Implement the Interface: Mismatched Method Parameters?. 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