Go language Practical Notes (eight) | Go Function method

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

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.

In the Go language, functions and methods are not quite the same, with a clear conceptual distinction. In other languages, such as Java, in general, functions are methods, methods are functions, but in the go language, functions refer to methods that do not belong to any structure or type, that is, the function is not a receiver, and the method has a receiver, and the method we say is either a struct Either belongs to a newly defined type.

Function

Functions and methods, although the concepts are different, but the definitions are very similar. The definition declaration of a function does not have a receiver, so we define the declaration directly in the go file, under the Go package.

12345678
func Main ()  {sum: = Add (12) fmt. Println (SUM)}funcaddint)int  {return A + b }

In the example, we define a add function whose function signature is func add(a, b int) int , without a receiver, directly under a package of go, which can be called directly, such as the function called in the example main add .

The function name in the example starts with lowercase add , so its scope is only used within the declared package and cannot be used by other packages, and if we start the function name with an uppercase letter, the scope of the function is larger and can be called by other packages. This is also the use of the case in the go language, such as Java, there are special keywords to declare the scope private , protect and public so on.

12345678910
/ * commonly used libraries, there are some common methods to facilitate the use of */package lib//an addition implementation //return value of A+b  func ADD  int) int  {return A + b}

The method defined in the example above Add can be called by another package.

Method

The declaration of a method is similar to a function, and the difference is that when a method is defined, it func adds a parameter to the method name, which is the recipient, so that the method we define is bound together with the receiver and is called the receiver's method.

1234567
type struct string}  func(P person)string()string  {return' Theperson ' name is ' +p.name}

Notice the func added parameter between the example and the method name (p person) , which is the receiver. Now we say that the type person has a String method, and now we look at how to use it.

1234
func Main ()  {p:=person{name:"Zhang San"}fmt. Println (P.string ())}

The method called is very simple and is called with a variable of type, and the type variable and method is preceded by an . operator that represents the meaning of a method to invoke the type variable.

There are two types of recipients in the Go language: The value recipient and the pointer recipient. In our example above, we use the example of the recipient of the value type.

Using a method defined by a value type receiver, when invoked, is actually a copy of the value recipient, so any operation on that value will not affect the original type variable.

1234567891011121314151617
func  main   ()   {p:=person{name:  "Zhang San" } P.modify () //value recipient, modified invalid  fmt. Println (P.string ())}type  person struct  {name string }func   (P person)  string   ()  string   {return   +p.name} func   (p person)  modify   ()   {p.name =  "John Doe" } 

The above example, the printed value or the 张三 modification to it is invalid. If we use a pointer as a receiver, it will work because the pointer recipient passes a copy of the pointer to the original value, a copy of the pointer, or a value of the original type, so when modified, it also affects the value of the original type variable.

1234567891011121314151617
func  main   ()   {p:=person{name:  "Zhang San" } P.modify () //pointer recipient, modifies valid  FMT. Println (P.string ())}type  person struct  {name string }func   (P person)  string   ()  string   {return   +p.name} func   (p *person)  modify   ()   {p.name =  "John Doe" } 

Just change it and become the recipient of the pointer and you can complete the modification.

When invoking a method, the recipient of the pass is essentially a copy, but one is a copy of the value, and the other is a copy of the value pointer. The pointer has an attribute that points to the original value, so modifying the value pointed to by the pointer modifies the original value. We can simply understand that the value recipient uses a copy of the value to invoke the method, and the pointer receiver uses the actual value to invoke the method.

In the above example, there is no finding that when we call the pointer receiver method, we use a variable that is also a value, not a pointer, if we use the following is also possible.

12
P:=person{name:"Zhang San"//pointer recipient, modify valid

It's also possible. If we do not enforce the use of pointers, the go compiler will automatically take pointers to meet the requirements of the receiver.

Similarly, if the method is a value recipient, the use of pointers can also be called, the Go compiler will automatically dereference to meet the requirements of the receiver, such as the method defined in the example String() , can also be called:

12
P:=person{name:"Zhang San"}fmt. Println ((&p). String ())

In short, the call to the method can use either a value or a pointer, and we do not have to strictly follow these, and the go language compiler will help us to automatically escape, which greatly facilitates our developers.

Whether you are using a value recipient or a pointer receiver, be sure to figure out the nature of the type: Do you want to change the current value when you manipulate the type, or do you want to create a new value to return? These can determine whether we are passing by value or by pointer.

Multi-value return

The go language supports a multivalued return of function methods, which means that our defined function methods can return multiple values, such as many of the methods in the standard library, return two values, the first is the value that the function needs to return, the second is the error message returned on error, the benefit of Our error exception information is no longer used in the same way as Java, the use of a exception such a heavy expression, very concise.

12345678
func Main ()  {file, err: = OS. Open ("/usr/tmp")ifnil {log. Fatal (Err)return}fmt. Println (file)}

If the value is returned, we do not want to use it and can be _ ignored.

1
File, _: = OS. Open ("/usr/tmp")

The definition returned by multiple values is also very simple, see an example.

123
func Add  int) (int, error)  {returnnil}

When a function method declaration is defined, it is separated by commas, because multiple returns are enclosed in parentheses. The returned value is also used as a return keyword, separated by commas, and the return declaration is in the same order.

Variable parameters

The parameters of a function method can be any number, which we call a variable parameter, such as a function that we commonly use fmt.Println() , to receive a mutable parameter.

123
func Main ()  {fmt. Println ("1","2","3")}

Parameters can be changed, can be any number. We can also define the definition of variable parameters, which can be variable, and add ellipses before the type ... Can.

12345678910
func Main ()  {print("1","2","3")}funcprint (A ... Interface {}){ for _,v:=range a{fmt. Print (v)}fmt. Println ()}

In the example we define a function that accepts a variable parameter, and the effect is the fmt.Println() same.

A mutable parameter is essentially an array, so we use it like an array, like a loop in an example for range .

There are some other knowledge points in the function method, such as painc exception handling, recursion, etc., which are not introduced in the "Go Language Combat" book, which can refer to the bible of the Go language.

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.

Scan code Attention

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.