Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Golang pulse method?

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the method of Golang pulse communication". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the method of Golang pulse communication"?

Catalogue

Method and recipient

Receiver of pointer type

The recipient of the value type

Methods and functions

Any type of adding method

Method inheritance

Method rewriting

Supplement of structures and methods

Method and recipient

A method in the Go language (Method) is a function that acts on a specific type of variable. This particular type of variable is called a Receiver. The concept of receiver is similar to this or self in other languages.

There are functions and methods in the Go language. One method is a function that contains the recipient, which can be a value or a pointer to a named type or struct type. All methods of a given type belong to the method set of that type

Method is just 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 access it inside the method.

Method can add new behavior to a user-defined type. The difference between it and a function is that a method has a receiver, add a receiver to a function, and it becomes a method. The receiver can be a value receiver or a pointer receiver.

When a method is called, the value type can call either the value receiver's method or the pointer receiver's method; the pointer type can call either the pointer receiver's method or the value receiver's method.

That is, regardless of the type of recipient of the method, the value and pointer of that type can be called and do not have to strictly match the type of the recipient.

The definition format of the method is as follows:

Func (t Type) methodName (parameter) (return) {}

Among them

T: when naming parameter variable names in the recipient, it is officially recommended to use lowercase of the first letter of the recipient type name, rather than names such as self, this, etc.

Type: the receiver type is similar to the parameter, and can be pointer type and non-pointer type.

MethodName, parameter, return: the specific format is the same as the function definition.

/ / Person structure type Person struct {name string age int8} / / NewPerson constructor func NewPerson (name string, age int8) * Person {return & Person {name: name, age: age,}} / / Dream Person dreaming method func (p Person) Dream () {fmt.Printf ("% s dream is to learn Go language!\ n", p.name)} func main () {p1: = NewPerson ("Zhang San", 25) p1.Dream ()}

The difference between a method and a function is that a function does not belong to any type, but a method belongs to a specific type.

You can define the same method name:

Type Rectangle struct {width, height float64} type Circle struct {radius float64} func (r Rectangle) area () float64 {return r.width * r.height} / / the method belongs to the method func (c Circle) area () float64 {return c.radius * c.radius * math.Pi} func main () {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 ())}

Running result:

Area of r1 is: 24

Area of r2 is: 36

Area of c1 is: 314.1592653589793

Area of c2 is: 1963.4954084936207

Although the name of method is exactly the same, if the recipient is different, then method is different.

The recipient's field can be accessed in the method

Call method to pass. Access, just like accessing fields in struct

Receiver of pointer type

The receiver of the pointer type consists of a pointer of a structure. because of the characteristics of the pointer, any member variable of the receiver pointer is modified when the method is called, and the modification is valid after the end of the method. This approach is very close to object-oriented this or self in other languages:

Type Rectangle struct {width, height int} func (r * Rectangle) setVal () {r.height = 20} func main () {p: = Rectangle {1,2} s: = p p.setVal () fmt.Println (p.height, s.height)}

Results:

20 2

The recipient of the value type

When the method acts on the receiver of the value type, the Go language makes a copy of the recipient's value while the code is running. The member value of the recipient can be obtained in the method of the receiver of the value type, but the modification operation is only for the copy and cannot modify the recipient variable itself.

Type Rectangle struct {width, height int} func (r Rectangle) setVal () {r.height = 20} func main () {p: = Rectangle {1,2} s: = p p.setVal () fmt.Println (p.height, s.height) / / 22}

When should the pointer type receiver be used

The value in the recipient needs to be modified

The recipient is a large object with high copy cost.

To ensure consistency, if one method uses a pointer receiver, then other methods should also use a pointer receiver.

Methods and functions

Why use methods when you already have a function?

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 () {emp1: = Employee {name: "Sam Adolf", salary: 5000, currency: "$" } displaySalary (emp1)}

In the above program, the displaySalary method is converted to a function, and Employee struct is passed to it as an argument. This program also produces the same output: Salary of Sam Adolf is $5000.

Why can you use functions to write the same program? There are several reasons:

Go is not a purely object-oriented programming language, it does not support classes. Therefore, a method of a type is a way to implement a class-like behavior.

Methods with the same name can be defined on different types, while functions with the same name are not allowed.

Any type of adding method

In the go language, the type of the receiver can be any type, not just a structure, any type can have a method. For example, we can use the type keyword to define a new custom type based on the built-in int type, and then add methods to our custom type.

/ / MyInt defines int as a custom MyInt type type MyInt int / / SayHello to add a SayHello method for MyInt func (m MyInt) SayHello () {fmt.Println ("Hello, I am an int.") } func main () {var M1 MyInt m1.SayHello () / / Hello, I am an int. M1 = 100 fmt.Printf ("% # v% T\ n", M1, M1) / / 100 main.MyInt}

Note: non-local types cannot define methods, which means we cannot define methods for other package types.

Method inheritance

Method is inheritable, and if an anonymous field implements a method, the struct that contains the anonymous field can also call the method

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 () {fmt.Printf ("Hi, I am% s you can call me on% s\ n", h.name, h.phone)} func main () {mark: = Student {Human {"Mark", 25, "222-222-YYYY"}, "MIT"} sam: = Employee {Human {"Sam", 45 "11-888-XXXX"}, "Golang Inc"} mark.SayHi () sam.SayHi ()

Running result:

Hi, I am Mark you can call me on 222-222-YYYYHi, I am Sam you can call me on 111-888-XXXX method rewriting

The method of 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} / / Human definition methodfunc (h * Human) SayHi () {fmt.Printf ("Hi, I am% s you can call me on% s\ n", h.name, h.phone)} / / Employee rewrites Human's methodfunc (e * Employee) SayHi () {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 () {mark: = Student {Human {" Mark ", 25," 222-222-YYYY "}," MIT "} sam: = Employee {Human {Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi () sam.SayHi ()}

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

Methods can be inherited and overridden

When there is an inheritance relationship, call it according to the nearest principle

Supplement of structures and methods

Because both slice and map data types contain pointers to the underlying data, be careful when you need to copy them:

Type Person struct {name string age int8 dreams [] string} func (p * Person) SetDreams (dreams [] string) {p.dreams = dreams} func main () {p1: = Person {name: "Zhang San", age: 18} data: = [] string {"eat", "sleep", "hit beans"} fmt.Printf ("% p\ n", data) / / 0xc00006e360 p1.SetDreams (data) / / passes the memory address of data Now p.dreams and data point to the same memory space fmt.Printf ("% p\ n", p1.dreams) / / 0xc00006e360 / / do you really want to modify p1.dreams? Data [1] = "do not sleep" / / the modification of the data value will affect the dream field fmt.Println (p1.dreams) / / [eat without sleep and play beans]} of the person structure.

The correct thing to do is to use a copy of the passed-in slice for structure assignment in the method.

Func (p * Person) SetDreams (dreams [] string) {p.dreams = make ([] string, len (dreams)) copy (p.dreams, dreams)}

The same problem exists in the case of returning values slice and map, which must be noted in the actual coding process.

At this point, I believe you have a deeper understanding of "what is the method of Golang pulse communication". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report