Last active
April 28, 2019 08:30
-
-
Save polebug/636d9fb68f6d26bd725394ff01a741fa to your computer and use it in GitHub Desktop.
学习 Go 的代码片段
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//函数不支持默认值参数,不支持函数重载 | |
//不支持在函数里嵌套一个命名函数定义,但是支持嵌套匿名函数,for example: anonymous := func(){} | |
package main | |
import "fmt" | |
//函数类型 | |
//两个函数类型相同指的是:形参列表和返回值列表`完全相同` | |
func funcType(para1, para2 int){ | |
return | |
} | |
//有名函数 | |
func namedFunc(para1, para2 int) int { | |
return para1 + para2 | |
} | |
//匿名函数 | |
var anonymous = func (para1, para2 int) int { | |
return para1 + para2 | |
} | |
//匿名函数作为参数 | |
func testAnonymousasPara(f func(int, int) int, para1 int, para2 int) int { | |
return f(para1, para2) | |
} | |
//匿名函数作为返回值 | |
func testAnonymousasReturn() func(int, int) int { | |
return func(para1, para2 int) int { | |
return para1 + para2 | |
} | |
} | |
func main(){ | |
//格式化打印函数的类型 | |
fmt.Printf("%T\n", funcType) | |
fmt.Println(namedFunc(1, 2)) | |
fmt.Println(anonymous(3, 4)) | |
fmt.Println(testAnonymousasPara(named_func, 5, 6)) | |
tmp := testAnonymousasReturn() | |
re := tmp(7, 8) | |
fmt.Println(re) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Go 函数实参到形参的传递都是`值拷贝` | |
// 只是有的是拷贝值,有的是拷贝地址值 | |
// 在函数调用时,像切片(slice)、字典(map)、接口(interface)、通道(channel)等这样的引用类型都是默认使用引用传递 | |
func chvalue(a int) int { | |
a = a + 1 | |
return a | |
} | |
func chpointer(a *int) int { | |
*a = *a + 1 | |
return *a | |
} | |
func main() { | |
var a int = 1 | |
value := chvalue(a) | |
fmt.Println(value, " ", a) | |
pointer := chpointer(&a) | |
fmt.Println(pointer, " ", a) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment