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.
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
Asked: 2023-06-22 09:31:58 +0000
Seen: 11 times
Last updated: Jun 22 '23
How can one ensure that sub-classes have uniform method parameters in TypeScript?
How can the calculation of matrix determinant be performed using CUDA?
How can code repetition be prevented when using (box)plot functions?
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?
How can circles be detected in openCV?
What is the method to determine the most precise categorization of data using Self Organizing Map?