Junior — Middle
What steps are needed to implement a method in a structure in Go language?
sobes.tech AI
Answer from AI
In Go language, a method is implemented as a function with a receiver, which links the method to a specific struct. To implement a method on a struct, follow these steps:
- Define the struct for which the method will be.
- Create a function with method syntax, specifying the receiver in parentheses before the function name.
- Inside the function, implement the necessary logic.
Example:
package main
import "fmt"
type Person struct {
Name string
}
// Method with value receiver
func (p Person) Greet() {
fmt.Printf("Hello, my name is %s\n", p.Name)
}
func main() {
person := Person{Name: "Ivan"}
person.Greet() // Outputs: Hello, my name is Ivan
}
You can also use a pointer receiver if the method needs to modify the struct's state.