Methods in Go
October 19, 2022Less than 1 minute
Methods in Go 관련
The Go Handbook – Learn Golang for Beginners
Golang is an awesome, simple, modern, and fast programming language. It’s compiled, open source, and strongly typed. Golang – also called Go – was created by Google engineers with these main goals: make their projects compile (and run) faster be sim...
The Go Handbook – Learn Golang for Beginners
Golang is an awesome, simple, modern, and fast programming language. It’s compiled, open source, and strongly typed. Golang – also called Go – was created by Google engineers with these main goals: make their projects compile (and run) faster be sim...
You can assign a function to a struct, and in this case we call it a method.
Example:
type Person struct {
Name string
Age int
}
func (p Person) Speak() {
fmt.Println("Hello from " + p.Name)
}
func main() {
flavio := Person{Age: 39, Name: "Flavio"}
flavio.Speak()
}
You can declare methods to be pointer receiver or value receiver.
The above example shows a value receiver. It receives a copy of the struct instance.
This would be a pointer receiver that receives the pointer to the struct instance:
func (p *Person) Speak() {
fmt.Println("Hello from " + p.Name)
}