---
title: "Go语言函数"
author: "guhao022"
date: "2014-08-07T11:36:43Z"
tags: []
categories: ["编程语言"]
slug: "go"
draft: false
lastmod: "2014-08-07T11:36:43Z"
id: 2101260
url: "https://guhao022.iteye.com/blog/2101260"
---

函数是Go语言里面的核心设计，它通过func来声明，函数可以有一个或者多个参数，每个参数后面都要带有类型，通过“,”分隔，可以返回多个值，函数的格式为：

```go
func funcName(input1 type1, input2 type2)(output1 type1, output2 type2){
    //处理逻辑代码
    //返回值
    return value1, value2
}
```

> 返回值声明了两个变量output1和output2，如果不想声明也可以，但是要保留两个类型声明

> 如果只有一个返回值且不声明返回值变量，可以省略“包括返回值”的括号

> 如果没有返回值就直接省略最后的返回信息

一个实际应用函数的例子（用来计算最大值）

```go
package main

import "fmt"

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func main() {
	x := 3
	y := 4
	z := 5
	max_xy := max(x, y) //调用函数 max(x, y)
	max_xz := max(x, z)
	fmt.Printf("max(%d,%d) = %d\n", x, y, max_xy)
	fmt.Printf("max(%d,%d) = %d\n", x, z, max_xz)
	fmt.Printf("max(%d,%d) = %d\n", y, z, max(y, z)) //直接调用
}
```

`多个返回值`

例子：

```go
package main

import "fmt"

//返回A+B和A*B
func sub(A, B int) (int, int) {
	return A + B, A * B
}
func main() {
	x := 3
	y := 4
	xPLUSy, xTIMESy := sub(x, y) //调用函数 sub(x, y)
	fmt.Printf("xPLUSy(%d,%d) = %d\n", x, y, xPLUSy)
	fmt.Printf("xTIMESy(%d,%d) = %d\n", x, y, xTIMESy)
}
```

`变参`

Go语言支持变参，接受变参的函数有不定数量的参数，为了做到这一点，首先需要定义函数使其接受变参。

```go
func myfunc(arg ...int) {}
```

arg ...int 告诉我们Go语言这个函数接受不定数量的参数。注意，这些参数的类型全部时int。在函数体中，变量arg时一个int的slice

```go
for _, n := arg {
    fmt.Printf("And the number is: %d\n", n)
}
```

 

`传值与指针`

函数的普通传值只是传值的copy，而实参不会变化，比如

```go
package main

import "fmt"

func add(a int) int {
	a = a + 1
	return a
}
func main() {
	x := 3
	fmt.Printf("x = %d\n", x)    //输出x=3
	x1 := add(x)                 //调用函数
	fmt.Printf("x+1 = %d\n", x1) //输出x+1=4
	fmt.Printf("x = %d\n", x)    //继续输出x，应该为x=3
}
```

如果想真正的传 x 本身的话就需要指针了，变量在内存中是存放于一定的地址上，修改变量实际是修改变量地址处的内存。

例子

```go
package main

import "fmt"

func add(a *int) int {
	*a = *a + 1 //修改了a的值
	return *a   //返回新值
}
func main() {
	x := 3
	fmt.Printf("x = %d\n", x)    //输出x=3
	x1 := add(&x)                //调用函数 传x的内存地址
	fmt.Printf("x+1 = %d\n", x1) //输出x+1=4
	fmt.Printf("x = %d\n", x)    //继续输出x，应该为x=4
}
```

这样就达到了修改x的目的。传指针的好处：可以使多个函数能操作同一个对象，可以传递体积大的结构体

 

`defer延迟语句`

当你进行一些打开资源的操作时，遇到错误需要提前返回，在返回前你需要关闭相应的资源，不然很容易造成资源泄露：

```go
func ReadWrite() bool {
    file.Open("file")
    defer file.Close()
    if failureX {
        return false
    }
    if failureY {
        return false
    }
    return true
}
```

如果有很多调用defer，那么defer采用后进先出模式

 

 

`发布于：`[http://www.golune.com/blog/content/c45ae5ed3c92d1277173d43fafba4a4b8652f](http://www.golune.com/blog/content/c45ae5ed3c92d1277173d43fafba4a4b8652f)