This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging
What is the method
The Go language has both functions and methods. A method is a function that contains a receiver, which can be either a value or a pointer to a named or struct type. All methods of a given type belong to the method set of that type. A method is simply a function with a special sink type that is written between the func keyword and the method name. The receiver can be a struct type or a non-struct type. The receiver can be accessed from within the method.
Method syntax
Define the syntax of the method
func (t Type) methodName(parameter list)(return list){}func funcName(parameter list)(return list){}Copy the code
Example code:
package main
import (
"fmt"
)
type Employee struct {
name string
salary int
currency string
}
/* displaySalary() method has Employee as the receiver type */
func (e Employee) displaySalary(a) {
fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
}
func main(a) {
emp1 := Employee {
name: "Sam",
salary: 5000,
currency: "$",
}
emp1.displaySalary() //Calling displaySalary() method of Employee type
}
Copy the code
You can define the same method name
Example code:
package main
import (
"fmt"
"math"
)
type Rectangle struct {
width, height float64
}
type Circle struct {
radius float64
}
func (r Rectangle) area(a) float64 {
return r.width * r.height
}
// This method belongs to an object of type Circle
func (c Circle) area(a) float64 {
return c.radius * c.radius * math.Pi
}
func main(a) {
r1 := Rectangle{12.2}
r2 := Rectangle{9.4}
c1 := Circle{10}
c2 := Circle{25}
fmt.Println("Area of r1 is: ", r1.area())
fmt.Println("Area of r2 is: ", r2.area())
fmt.Println("Area of c1 is: ", c1.area())
fmt.Println("Area of c2 is: ", c2.area())
}
Copy the code
The results
Area of r1 is: 24
Area of r2 is: 36
Area of c1 is: 314.1592653589793
Area of c2 is: 1963.4954084936207
Copy the code
- Although the names of methods are identical, if the recipients are different, then methods are different
- Method specifies the field in which the receiver can be accessed
- Call method to pass. Accesses, just like fields are accessed in structs
Methods and functions
Why use methods when we already have functions?
Example code:
package main
import (
"fmt"
)
type Employee struct {
name string
salary int
currency string
}
/* displaySalary() method converted to function with Employee as parameter */
func displaySalary(e Employee) {
fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
}
func main(a) {
emp1 := Employee{
name: "Sam",
salary: 5000,
currency: "$",
}
displaySalary(emp1)
}
Copy the code
In the above program, the displaySalary method is converted to a function, and the Employee struct is passed to it as an argument. This program also produces the same output: Salary of Sam is $5000.
Why can we write the same program using functions? There are several reasons
- Go is not a pure object-oriented programming language; it does not support classes. Thus, a method of a type is a way to implement behavior similar to that of a class.
- Methods with the same name can be defined on different types, while functions with the same name are not allowed. Suppose we have a square and a circle. You can define a method called Area on squares and circles. This is done in the following program.
Variable scope
Scope is the scope in source code of a constant, type, variable, function, or package represented by a declared identifier.
In Go, variables can be declared in three places:
- Variables defined within a function are called local variables
- Variables defined outside a function are called global variables
- The variables in a function definition are called formal parameters
A local variable
Variables declared in the body of a function are called local variables. They are scoped only in the body of the function. Parameter and return value variables are also local variables.
The global variable
Variables declared outside the body of a function are called globals. They can be used throughout the entire package or even outside the package (after being exported).
package main
import "fmt"
/* Declare global variables */
var g int
func main(a) {
/* Declare a local variable */
var a, b int
/* Initialization parameters */
a = 10
b = 20
g = a + b
fmt.Printf("A = %d, b = %d and g = %d\n", a, b, g)10, b = 20 and g = 30
Copy the code
Formal parameters
Formal arguments are used as local variables to the function
Pointer as receiver
If you do not use the pointer as the receiver, you are only getting a copy without actually changing the data in the receiver
func (b *Box) SetColor(c Color) {
b.color = c
}
Copy the code
The sample code
package main
import (
"fmt"
)
type Rectangle struct {
width, height int
}
func (r *Rectangle) setVal(a) {
r.height = 20
}
func main(a) {
p := Rectangle{1.2}
s := p
p.setVal()
fmt.Println(p.height, s.height)
}
Copy the code
The results of
20 2
Copy the code
If you don’t have that *, it’s going to be 2, 2
Method inheritance
Methods are inheritable. If an anonymous field implements a method, then the struct containing the anonymous field can also call the method
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Student struct {
Human // Anonymous field
school string
}
type Employee struct {
Human // Anonymous field
company string
}
func (h *Human) SayHi(a) {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
func main(a) {
mark := Student{Human{"Mark".25."222-222-YYYY"}, "MIT"}
sam := Employee{Human{"Sam".45."111-888-XXXX"}, "Golang Inc"}
mark.SayHi()
sam.SayHi()
}
Copy the code
Running result:
Hi, I am Mark you can call me on 222- 222.-YYYY
Hi, I am Sam you can call me on 111- 888.-XXXX
Copy the code
Method to rewrite
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Student struct {
Human // Anonymous field
school string
}
type Employee struct {
Human // Anonymous field
company string
}
/ / the Human definition method
func (h *Human) SayHi(a) {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Employee method overwrites Human method
func (e *Employee) SayHi(a) {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone) //Yes you can split into 2 lines here.
}
func main(a) {
mark := Student{Human{"Mark".25."222-222-YYYY"}, "MIT"}
sam := Employee{Human{"Sam".45."111-888-XXXX"}, "Golang Inc"}
mark.SayHi()
sam.SayHi()
}
Copy the code
Running result:
Hi, I am Mark you can call me on 222- 222.-YYYY
Hi, I am Sam, I work at Golang Inc. Call me on 111- 888.-XXXX
Copy the code
- Methods can be inherited and overridden
- When there is inheritance relationship, the call is made according to the nearest principle, that is, the one with the same attribute name that is the most recent is used for the call.