内容纲要

引用类型

[cc lang=”go”]
package main

import “fmt”

func main() {
m := make(map[string]int)
changeMe(m)
fmt.Println(m[“Todd”]) // 44
}

func changeMe(z map[string]int) {
z[“Todd”] = 44
}

/*
Allocation with make
Back to allocation. The built-in function make(T, args)
serves a purpose different from new(T). It creates slices, maps, and channels only,
and it returns an initialized (not zeroed) value of type T (not *T). The reason for
the distinction is that these three types represent, under the covers, references to data structures
that must be initialized before use. A slice, for example, is a three-item descriptor containing
a pointer to the data (inside an array), the length, and the capacity, and until those items are initialized,
the slice is nil. For slices, maps, and channels, make initializes the internal data structure and prepares
the value for use.
*/
// https://golang.org/doc/effective_go.html#allocation_make
[/cc]

[cc lang=”go”]
package main

import “fmt”

func main() {
m := make([]string, 1, 25)
fmt.Println(m) // [ ]
changeMe(m)
fmt.Println(m) // [Todd]
}

func changeMe(z []string) {
z[0] = “Todd”
fmt.Println(z) // [Todd]
}

[/cc]

结构体指针

[cc lang=”go”]
package main

import “fmt”

type customer struct {
name string
age int
}

func main() {
c1 := customer{“Todd”, 44}
fmt.Println(&c1.name) // 0x8201e4120

changeMe(&c1)

fmt.Println(c1) // {Rocky 44}
fmt.Println(&c1.name) // 0x8201e4120
}

func changeMe(z *customer) {
fmt.Println(z) // &{Todd 44}
fmt.Println(&z.name) // 0x8201e4120
z.name = “Rocky”
fmt.Println(z) // &{Rocky 44}
fmt.Println(&z.name) // 0x8201e4120

}

[/cc]

可变参数

[cc lang=”go”]
package main

import “fmt”

func main() {
n := average(43, 56, 87, 12, 45, 57)
fmt.Println(n)
}

func average(sf …float64) float64 {
fmt.Println(sf)
fmt.Printf(“%T \n”, sf)
var total float64
for _, v := range sf {
total += v
}
return total / float64(len(sf))
}

[/cc]

[cc lang=”go”]
package main

import “fmt”

func main() {
data := []float64{43, 56, 87, 12, 45, 57}
n := average(data…)
fmt.Println(n)
}

func average(sf …float64) float64 {
total := 0.0
for _, v := range sf {
total += v
}
return total / float64(len(sf))
}

[/cc]

切片参数

[cc lang=”go”]
package main

import “fmt”

func main() {
data := []float64{43, 56, 87, 12, 45, 57}
n := average(data)
fmt.Println(n)
}

func average(sf []float64) float64 {
total := 0.0
for _, v := range sf {
total += v
}
return total / float64(len(sf))
}

[/cc]

发表评论

电子邮件地址不会被公开。 必填项已用*标注