1. map指针数组

代码

1
2
3
4
type As struct {
	A int
	B string
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func NewMapPointSlice() (r []*As) {
	i := 0
	for i=0; i < 5; i++ {
		a := &As{
			A: i,
			B: fmt.Sprintf("aaa:%d", i),
		}
		r = append(r, a)
	}
	return
}

test测试:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func TestNewMapPointSlice(t *testing.T) {
	as := NewMapPointSlice()
	for i, a := range as {
		t.Log(a)
		a.A = i+8
	}
	t.Log("\n============ \n")
	for _, a := range as {
		t.Log(a)
	}
}

结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
== RUN   TestNewMapPointSlice
    map_test.go:8: &{0 aaa:0}
    map_test.go:8: &{1 aaa:1}
    map_test.go:8: &{2 aaa:2}
    map_test.go:8: &{3 aaa:3}
    map_test.go:8: &{4 aaa:4}
    map_test.go:11: 
        ============ 
        
    map_test.go:13: &{8 aaa:0}
    map_test.go:13: &{9 aaa:1}
    map_test.go:13: &{10 aaa:2}
    map_test.go:13: &{11 aaa:3}
    map_test.go:13: &{12 aaa:4}
--- PASS: TestNewMapPointSlice (0.00s)
PASS

2. map数组

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func NewMapSlice() (r []As) {
	i := 0
	for i=0; i < 5; i++ {
		a := As{
			A: i,
			B: fmt.Sprintf("aaa:%d", i),
		}
		r = append(r, a)
	}
	return
}

test测试:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func TestNewMapSlice(t *testing.T) {
	as := NewMapSlice()
	for i, a := range as {
		t.Log(a)
		a.A = i+8
	}
	t.Log("\n============ \n")
	for _, a := range as {
		t.Log(a)
	}
}

结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
=== RUN   TestNewMapSlice
    map_test.go:20: {0 aaa:0}
    map_test.go:20: {1 aaa:1}
    map_test.go:20: {2 aaa:2}
    map_test.go:20: {3 aaa:3}
    map_test.go:20: {4 aaa:4}
    map_test.go:23: 
        ============ 
        
    map_test.go:25: {0 aaa:0}
    map_test.go:25: {1 aaa:1}
    map_test.go:25: {2 aaa:2}
    map_test.go:25: {3 aaa:3}
    map_test.go:25: {4 aaa:4}
--- PASS: TestNewMapSlice (0.00s)
PASS