Home >Backend Development >Golang >Why Does My Go Method with a Pointer Receiver Fail to Implement an Interface?

Why Does My Go Method with a Pointer Receiver Fail to Implement an Interface?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 15:47:11447browse

Why Does My Go Method with a Pointer Receiver Fail to Implement an Interface?

Golang Method with Pointer Receiver [Duplicate]

Problem:

In Go, when creating a method with a pointer receiver and implementing an interface, the following error can occur:

cannot use obj (type Implementation) as type IFace in return argument: Implementation does not implement IFace (GetSomeField method has pointer receiver)

Answer:

To resolve this error, ensure that the pointer to the struct implements the interface. This allows the method to modify the fields of the actual instance without creating a copy.

Code Modification:

Replace the offending line with:

return &obj

Explanation:

By returning a pointer to the struct, it implements the interface while allowing the method to modify the actual instance.

Example (Modified):

package main

import (
    "fmt"
)

type IFace interface {
    SetSomeField(newValue string)
    GetSomeField() string
}

type Implementation struct {
    someField string
}

func (i *Implementation) GetSomeField() string {
    return i.someField
}

func (i *Implementation) SetSomeField(newValue string) {
    i.someField = newValue
}

func Create() *Implementation {
    return &Implementation{someField: "Hello"}
}

func main() {
    var a IFace
    a = Create()
    a.SetSomeField("World")
    fmt.Println(a.GetSomeField())
}

By using a pointer receiver and ensuring the pointer implements the interface, you can successfully modify the actual instance of the struct while implementing the required methods.

The above is the detailed content of Why Does My Go Method with a Pointer Receiver Fail to Implement an Interface?. 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