【Go】method

go method

go no class !!!

But you can define methods for struct types

Methods are a class of functions with special receiver parameters

The method receiver is in the function list, between the func keyword and the method name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
  "fmt"
  "math"
)

type Vertex struct {
  X, Y float64
}

func (v Vertex) Abs() float64 {
  return math.Sqrt(v.X * v.X + v.Y * v.Y)
}

func main() {
  v: = Vertex {3, 4}
  fmt.Println(v.Abs())
}

Save as helloworld.go and execute the result

1
2
[me @ VM_0_14_centos go] # go run helloworld.go
5

In the above example, Abs has a receiver named v with type Vertex

Of course, a method is also a function, it just takes the receiver

We can also declare methods for non-struct types
And we can only declare methods for receivers of types defined in the same package

1
2
3
4
5
type MyFloat float64

func (f MyFloat) Abs() float64 {
  return float64(f)
}

Pointer receiver

Even we declare methods for pointer receivers

1
2
3
4
5
6
7
8
type Vertex struct {
  X, Y float64
}

func (v * Vertex) Abs(f float64) {
  v.X = v.X * f
  v.Y = v.Y * f
}

The method of the pointer receiver can modify the value pointed to by the receiver, just like the modification made in the Abs method.
Because methods often need to modify their receivers, pointer receivers are more commonly used

Persist in original technology sharing, your support will encourage me to continue to create!