Created
April 15, 2013 08:27
-
-
Save achun/5386703 to your computer and use it in GitHub Desktop.
测试 GoLang 下,指针,map,struct,数组,对象点操作"."
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" | |
"runtime" | |
) | |
type LogHour struct { | |
pv uint32 | |
} | |
type LogDay struct { | |
hours [24]LogHour | |
} | |
type PLogDay struct { | |
hours [24]*LogHour | |
} | |
func main() { | |
mem("before test") | |
test5() | |
mem("after test") | |
} | |
func mem(suffix string) { | |
mem := runtime.MemStats{} | |
runtime.ReadMemStats(&mem) | |
fmt.Println(mem.TotalAlloc, ":", "Memory TotalAlloc", suffix) | |
} | |
//不使用 map 和 指针 的情况 | |
func test0() { | |
m := LogDay{} | |
fmt.Println(m) | |
m.hours[10].pv++ // 可以操作 | |
fmt.Println(m) | |
} | |
//不使用 map 在 struct 中使用指针的情况 | |
func test1() { | |
m := PLogDay{} | |
fmt.Println(m) | |
m.hours[10] = &LogHour{} | |
m.hours[10].pv++ | |
fmt.Println(m) | |
fmt.Println(m.hours[10]) | |
} | |
// 使用 map | |
func test2() { | |
m := map[uint32]uint32{} | |
fmt.Println("m.len=", len(m)) | |
fmt.Println(m) | |
fmt.Println(m[1<<32-1]) // 虽然没有建立,但是可以访问 | |
m[10] = 222 | |
fmt.Println("m.len=", len(m)) | |
fmt.Println(m) | |
} | |
// 使用 map 不使用指针的访问与赋值 | |
func test3() { | |
m := map[uint32]LogDay{} | |
fmt.Println(m) | |
m[10] = LogDay{} | |
fmt.Println(m) | |
fmt.Println(m[10].hours[0].pv) // 可以访问但不能赋值,没有现实意义 | |
//m[10].hours[0] = LogHour{} // build失败:cannot assign ... | |
} | |
// 使用 map 在 struct 中使用指针 | |
func test4() { | |
m := map[uint32]PLogDay{} | |
fmt.Println(m) | |
m[10] = PLogDay{} | |
fmt.Println(m) | |
fmt.Println(m[10].hours) //可以访问 | |
//m[10].hours[0] = &LogHour{} //build失败:cannot assign ... | |
} | |
//在 map 中使用指针 | |
func test5() { | |
m := map[uint32]*LogDay{} | |
fmt.Println(m) | |
m[10] = &LogDay{} // 指针引用 | |
fmt.Println(m) | |
fmt.Println(m[10]) | |
m[10].hours[10].pv++ // 可以操作 | |
fmt.Println(m[10]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment