Sobes.tech
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:

  1. Define the struct for which the method will be.
  2. Create a function with method syntax, specifying the receiver in parentheses before the function name.
  3. 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.

What steps are needed to implement a method in a… - sobes.tech