Use of Go functions

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

Familiar with the syntax structure of Go function

Because go does not have a class concept, it uses structs to simulate. The functions in the code calculate the square root of the two integers and the absolute value of the values respectively.

Package Mainimport ("FMT" "math") type myfloat float64type Vertex struct {X, Y Float64}//vertex pointer corresponding abs method func (v *vertex) Ab S () float64 {return math. SQRT (v.x*v.x + v.y*v.y)}//myfloat structural Body corresponding ABS method func (F Myfloat) abs () Float64 {if f < 0 {return float64 (-f)}return float64 (f)} Func Main () {V: = &vertex{6, 4}//gets pointer to Vertex struct FMT.PRINTLN (V.abs ()) F: = Myfloat (-math. SQRT2)//Take 2 square root FMT. Println ("Float abs=", F.abs ())}

The significance of defining the corresponding method here is to manipulate the original object. If you define a method that corresponds to a struct type, the passed argument is a copy of the struct, not the original object. We can add a method as follows:

Package Mainimport ("FMT" "math") type myfloat float64type Vertex struct {X, Y Float64}//vertex pointer corresponding abs method func (v *vertex) Ab S () float64 {return math. SQRT (v.x*v.x + v.y*v.y)}//vertex pointer corresponds to the Add method func (v *vertex) Add (f float64) {v.x = FV. Y + = f}//myfloat Structure corresponding ABS method func (F Myfloat) abs () Float64 {if f < 0 {return float64 (-f)}return float64 (f)}func main () { V: = &vertex{6, 4}//gets pointer to Vertex struct FMT.PRINTLN (V.abs ()) V.add (3.14) fmt. Println (v) F: = Myfloat (-math. SQRT2)//Take 2 square root FMT. Println ("Float abs=", F.abs ())}

After running, the values of x and y inside the object v have been changed.



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.