A method is just a function with a special receiver type between the func
keyword and the method name. The receiver can either be a struct type or non-struct type.
The syntax of a method declaration is provided below.
func (t Type1) methodName(parameter list) Type2 { }
When you create a method in your code the receiver and receiver type must be present in the same package. And you are not allowed
to create a method in which the receiver type is already defined in another package
including inbuilt type like int, string, etc.
type Employee struct {
name string
salary int
currency string
}
/*
displaySalary() method has Employee as the receiver type
*/
func (e Employee) displaySalary() {
fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
}
func main() {
emp1 := Employee {name:"Sam Adolf", salary:5000, currency: "$",}
emp1.displaySalary() //Calling displaySalary() method of Employee type
}