Ask Your Question
3

How can the value of a field in a struct within an interface be accessed and modified in Golang?

asked 2023-06-22 09:31:58 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-22 09:37:01 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-22 09:31:58 +0000

Seen: 11 times

Last updated: Jun 22 '23