Go Language method

Source: Internet
Author: User
Method

Go has no class. However, you can still define a method on a struct type.

The method recipient appears in the argument between the Func keyword and the method name.

Case a----object

Package main

Import (
	"FMT"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v * Vertex) Abs () float64 {//pointer type return
	math. SQRT (v.x*v.x + v.y*v.y)
}

func main () {
	V: = &vertex{3, 4}
	FMT. Println (V.abs ())
}
Case two----common type

Package main

Import (
	"FMT"
	"math"
)

type myfloat float64

func (f myfloat) Abs () float64 {//value type
	if f < 0 {return
		float64 (-f)
	} return
	float64 (f)}

func main () {
	f: = MYFL Oat (-math. SQRT2)
	FMT. Println (F.abs ())
}
this defines 2 methods of passing type parameters, one on the *vertex pointer type and the other on the Myfloat value type. The difference is as follows

1. Values passed by value type are only useful on the current method

2. The pointer type is passed a memory address, so when any parameter value in the structure is modified in the method, it is directly stored in the structure.

Case:

Package main

Import (
	"FMT"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v * Vertex) Scale (f float64) {
	v.x = v.x * F
	v.y = V.y * F
}

func (v *vertex) Abs () float64 {
	return Math. SQRT (v.x*v.x + v.y*v.y)
}

func main () {
	V: = &vertex{3, 4}
	FMT. Printf ("Before scaling:%+v, Abs:%v\n", V, V.abs ())
	V.scale (5)   
	A method for modifying the value of a struct parameter is called here, and when the method associated with V *vertex is the pointer type, the value of the object in V will be changed and the resulting ABS method output is 25.
	//If we remove the pointer * number, the Vertex associated with this method is actually a copy of the &vertex{3, 4}
	At this point in the scale method to modify the value of the object is not effective, it can not be passed to the back of the ABS method, at this time the return of the ABS results are still 5
	FMT. Printf ("After scaling:%+v, Abs:%v\n", V, V.abs ())
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.