package main
import (
"fmt"
)
func printSlice(a []int32) {
fmt.Println(a)
fmt.Printf("%p, %d, %d\n", a, len(a), cap(a))
}
// slice의 원본과 사본에 동시 작업시에 문제를 확인하기 위한 코드
type ts struct {
s []int32
}
func testSliceInStruct() {
t := &ts {
s: make([]int32, 0, 5),
}
t.s = append(t.s, 5)
a := t.s
printSlice(a)
printSlice(t.s)
a = append(a, 0, 1, 2)
printSlice(a)
printSlice(t.s)
b := &(t.s)
*b = append(*b, 2)
printSlice(a)
printSlice(t.s)
printSlice(*b)
}
// slice의 원본과 사본에 동시 작업시에 문제를 확인하기 위한 코드
var a = make([]int32, 0, 13)
func aaa(b int32) {
a = append(a, b)
}
func testSlice() {
a = append(a, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
printSlice(a)
//*
b := a
for i := len(b) - 1; i >= 0; i-- {
// for i := 0; i < len(b); i++ {
if b[i] % 2 == 0 {
// 원본(a)에 작업
aaa(b[i])
// 사본(b)에 작업
b = append(b[:i], b[i+1:]...)
}
}
printSlice(b)
/*/
// 원본과 사본에 동시 작업 문제를 해결하기 위해
// 원본의 포인터를 가지고 사본 문제를 해결
b := &a
for i := len(*b) - 1; i >= 0; i-- {
// for i := 0; i < len(b); i++ {
if (*b)[i] % 2 == 0 {
aaa((*b)[i])
(*b) = append((*b)[:i], (*b)[i+1:]...)
}
}
printSlice(*b)
//*/
//a = b
printSlice(a)
}
// map의 value에 slice의 포인터를 넣어서 map 순행시에도 원본에 접근할 수 있게 함.
var m = make(map[int32]*[]int32)
func testMapNSlice() {
m[10] = &[]int32{}
*m[10] = make([]int32, 0, 10)
*m[10] = append(*m[10], 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
printSlice(*m[10])
for key, txs := range m {
for i := len(*txs) - 1; i >= 0; i-- {
if (*txs)[i] % 2 == 0 {
*m[key] = append(*m[key], (*txs)[i])
*txs = append((*txs)[:i], (*txs)[i+1:]...)
}
}
printSlice(*m[key])
printSlice(*txs)
}
}
func main() {
//testSliceInStruct()
testSlice()
//testMapNSlice()
}
'GoLang' 카테고리의 다른 글
Go channel 테스트 코드 (0) | 2018.09.20 |
---|