Go Language Learning Notes---functions

Source: Internet
Author: User
Tags php class sprintf
This is a creation in Article, where the information may have evolved or changed. function
Definition of a function
there are two reserved functions in go: Init function (can be applied to all the package ) and main function (applies only to package main ). These two functions cannot have any parameters and return values when they are defined. The go program will automatically call Init () and Main () , so you don't need to call these two functions anywhere. each package in the init functions are optional, but package main You must include a main function.
Go a very special feature (for compiled languages) is that functions and methods can return multiple valuesExample: Package Mainvar a IntFunc main () {s: = factorial (4) println (s)}func factorial (x int) (int) {var result int if x = = 0 {result = 1} else {result = X * factorial (X-1)} return result} output: 24
can also be replaced by: Package Mainvar a IntFunc main () {s: = factorial (4) println (s)}func factorial (x int) (result int) {if x = = 0 {result = 1} else {result = X * factorial (X-1)} return} output result: 24
Delay CodeFunc ReadWrite () bool {file. Open ("file")//Do some work if Failurex { file. Close ()return false} if Failurey { file. Close ()return false} file. Close () return true} There is a lot of duplicate code here. To solve this, Go has a defer statement. The function specified after defer is called before the function exits. Can be changed to the following code: Func ReadWrite () bool {file. Open ("file") defer file. Close ()File. Close () is added to the defer list//do some work if Failurex {return False Close () is now automatically called} if Failurey {Retu RN false here is also} return true}
Defer is somewhat similar to the __destruct () destructor in the PHP class defer can also be written like this:
defer func (x int) {/* ... */} (5)
Assign a value of 5 to the input parameter X
If there are many calls to defer, then defer is in LIFO mode, so the following code will output 4 3 2 1 0 for I: = 0; I < 5; i++ { Defer FMT. Printf ("%d", I)}
Example: Package Mainvar a IntFunc main () {s: = Test (2) println (s)}func test (i int) (t int) {defer func () {t++ } () T = i+1 return} output Result: 4
Example 2:package Mainvar a IntFunc main () {s: = Test (2) println (s)}func test (i int) (t int) {defer func (x int) { T + = x} (5) T = i+1 return} output Result: 8
Attention: If there are many calls to defer, so defer is to use the LIFO modeExample 3:package MainFunc Main () {for j: = 0; J < 5; J + + { Defer println (j)}} output Result: 43210

variable parameterThe function that accepts the argument is a variable number of arguments. To do this, you first need to define the function to accept the argument: Func myfunc (arg ... int) {} arg ... int tells Go that the function accepts an indefinite number of arguments. Note that the types of these parameters are all int. In the function body, the variable arg is an int of type Slice example: Package Mainimport "FMT" Func Main () {test ("a", "B")}func Test (Arg ... string) {for _, Val: = Range arg{FMT. Printf ("%s\n", Val)}}
Output Result: AB
function as a valueThe example above can also be: Package Mainimport "FMT" Func Main () {demo: = Func (Arg ... string) {//defines an anonymous function and assigns a value to the demo for _, VA L: = Range arg{FMT. Printf ("%s\n", Val)}} demo ("A", "B")} Output Result: AB
Functions as values can also be used elsewhere, such as map. Example: Package Mainimport "FMT" Func Main () {map1: = Map[int] func (i int) (int) {1:func (x int) (int) {return x+1} , 2:func (y int) (int) {return y+2}, 3:func (z int) (int) {return z+3},} fmt. Printf ("%d\n", Map1[1] (1)) fmt. Printf ("%d\n", Map1[2] (1)) fmt. Printf ("%d\n", Map1[3] (1))} Output Result: 234
callback function
Example: Package Mainimport "FMT" Func Main () {callback (2, PrintIt)}func printit (x int) {FMT. Printf ("%d\n", X)}
Func callback (y int, f func (int)) {f (Y)} output Result: 2
Example 2:package mainimport "FMT" Func Main () {callback (2, PrintIt)}func printit (x int) (demo int) {demo = x + 1 return}
Func callback (y int, f func (int)) {result: = f (y) Res: = FMT. Sprintf ("%d", result) + "demo"//Sprintf () converts int to a string fmt. Printf ("%s\n", res)} output result: 3demo
Example 3:
package mainimport "fmt"//简单的一个函数,实现了参数+1的操作func add1(a *int) int { // 请注意, *a = *a+1 // 修改了a的值 return *a // 返回新值}func main() { x := 3 fmt.Println("x = ", x) // 应该输出 "x = 3" x1 := add1(&x) // 调用 add1(&x) 传x的地址 fmt.Println("x+1 = ", x1) // 应该输出 "x+1 = 4" fmt.Println("x = ", x) // 应该输出 "x = 4"}



Related Article

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.