Receiver Functions:
Function Receiver sets a method on variables we create.
syntax:
func(t type) functionName() {}
code:
employee.go
package employee import "fmt" // Employee struct type employee struct { name string age int salary int } // constructor func NewEmployee(name string, age int, salary int) *employee { return &employee{ name: name, age: age, salary: salary, } } // print employee func (e employee) ToString() { fmt.Printf("%s is %d years old with salary %d \n", e.name, e.age, e.salary) }
- Notice the ToString() method in employee.go, it is the receiver's function for employee type
- So any new variable of type employee will have access to the 'ToString()' method
main.go
package main import "trygo/employee" func main() { rake := employee.NewEmployee("Rake", 13, 4566) rake.ToString() }
- Calling receiver's function for type employee using rake.ToString()
output:
~/projects/go/src/trygo$ go run main.go Rakesh is 13 years old with salary 4566
- The usage of receiver's function is best seen when we use interfaces in Go. I'll visit this in more detail when i write about interfaces in future. For now here's a quick sneak peak of the concept
When you use receiver function along with an interface, it is that at the time of the call, the receiver is an interface and the function to be called is determined dynamically
Happy Coding 🤖
Comments
Post a Comment