Skip to content

Instantly share code, notes, and snippets.

@archever
Last active September 18, 2018 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archever/f89578135d6bdff12dc323cbe8f72d49 to your computer and use it in GitHub Desktop.
Save archever/f89578135d6bdff12dc323cbe8f72d49 to your computer and use it in GitHub Desktop.
golang 参数传递
package main
import (
"log"
)
func main() {
i := [...]int{1, 2, 3}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i [3]int) {
i[0]++
log.Printf("in show: %v", i)
}
// 2018/09/18 10:57:28 before show: [1 2 3]
// 2018/09/18 10:57:28 in show: [2 2 3]
// 2018/09/18 10:57:28 after show: [1 2 3]
package main
import (
"log"
)
func main() {
i := &[...]byte{1, 2, 3}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i *[3]byte) {
i[0]++
log.Printf("in show: %v", i)
}
// 2018/09/18 11:12:46 before show: &[1 2 3]
// 2018/09/18 11:12:46 in show: &[2 2 3]
// 2018/09/18 11:12:46 after show: &[2 2 3]
package main
import (
"log"
)
func main() {
i := map[string]int{"a": 1, "b": 2}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i map[string]int) {
i["a"]++
log.Printf("in show: %v", i)
}
// 2018/09/18 11:01:30 before show: map[a:1 b:2]
// 2018/09/18 11:01:30 in show: map[a:2 b:2]
// 2018/09/18 11:01:30 after show: map[a:2 b:2]
package main
import (
"log"
)
func main() {
i := []int{1, 2, 3}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i []int) {
i[0]++
log.Printf("in show: %v", i)
}
// 2018/09/18 10:57:28 before show: [1 2 3]
// 2018/09/18 10:57:28 in show: [2 2 3]
// 2018/09/18 10:57:28 after show: [2 2 3]
package main
import (
"log"
)
type test struct {
Name string
Value int
}
func main() {
i := test{"a", 1}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i test) {
i.Value++
log.Printf("in show: %v", i)
}
// 2018/09/18 11:03:46 before show: {a 1}
// 2018/09/18 11:03:46 in show: {a 2}
// 2018/09/18 11:03:46 after show: {a 1}
package main
import (
"log"
)
type test struct {
Name string
Value int
}
func main() {
i := &test{"a", 1}
log.Printf("before show: %v", i)
show(i)
log.Printf("after show: %v", i)
}
func show(i *test) {
i.Value++
log.Printf("in show: %v", i)
}
// 2018/09/18 11:04:59 before show: &{a 1}
// 2018/09/18 11:04:59 in show: &{a 2}
// 2018/09/18 11:04:59 after show: &{a 2}

值类型

  • int float string 不可寻址 复制值
  • array struct 复制值

引用类型

  • map slice chan 复制引用

指针类型

  • *array *struct 复制指针
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment