Method of Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Method

Go does not has classes. However, you can define methods on types.

Package Mainimport ("FMT"    "Math") Type Vertexstruct{X, Y float64}func (v Vertex) Abs () float64 {returnMath. SQRT (v.x*v.x + v.y*v.y)} Func (v*Vertex) Scale (f float64) {v.x= v.x *F v.y= V.y *F}func (v Vertex) Scalevalue (f float64) {v.x= v.x *F v.y= V.y *F}func Main () {V:= vertex{3,4} fmt. Println (V.abs ()) V.scale (2) fmt. Println (V.abs ()) V.scalevalue (2) fmt. Println (V.abs ()) P:= &v P.scale (2) fmt. Println (P.abs ())}

The output is as follows:

5
10
10
20

Three points of note:

1. Methods with pointer receivers can modify the value to which the receiver points.

2. Methods with pointer receivers take either a value or a pointer as the receiver when they is called:

var v Vertexv.scale (5)  // OKP: = &VP. Scale (ten//  OK

3. Methods with value receivers take either a value or a pointer as the receiver when they is called:

var/  OKp: = &//  OK

Interface

Package Mainimport ("FMT") Type IInterface{M ()}type Tstruct{Sstring}func (t*T) M () {fmt. Println (T.S)}func main () {varI i t:= t{"Hello"} i= &T I.M () V:= t{" World"} i=v I.M ()}

The second half of the code in the main function will cause an error: Cannot use V (type T) as type I in assignment:t does not implement I (M method have pointer receiver)

If you change the receiver type of M to value:

Func (T-T) M () {    fmt. Println (T.S)}

The code for the main function will run normally.

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.