Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To access and modify the value of a field in a struct within an interface in Golang, we need to define a method within the interface that allows us to do so.

For example, let's say we have an interface called Animal that includes a field Name of type string:

type Animal interface {
    GetName() string
    SetName(name string)
}

Now, we can define a struct that implements this interface:

type Dog struct {
    name string
}

func (d *Dog) GetName() string {
    return d.name
}

func (d *Dog) SetName(name string) {
    d.name = name
}

In this case, the GetName method returns the current value of the name field, and the SetName method sets the value of the name field to the parameter passed in.

To access and modify the value of the name field in a Dog instance, we can simply call the GetName and SetName methods:

dog := &Dog{name: "Fido"}
fmt.Println(dog.GetName()) // Output: Fido

dog.SetName("Rex")
fmt.Println(dog.GetName()) // Output: Rex

Here, we create a Dog instance with the name "Fido", and then we call the GetName method to retrieve its name. We then call the SetName method to change its name to "Rex", and call GetName again to check that the change was successful.