SoFunction
Updated on 2025-04-12

golang  Solve the problem of pointer data coverage

Scene

1. Settings

var stringPool = {
	New: func() any {
		return new([]string)
	},
}

func NewString() *[]string {
	v := ().(*[]string)
	return v
}

func PutString(s *[]string) {
	if s == nil {
		return
	}

	if cap(*s) > 2048 {
		s = nil
	} else {
		*s = (*s)[:0]
		(s)
	}
}

2. Use

func Test_Pool(t *) {
	dataSlice1 := demoData()
	dataSlice2 := demoData()
	dataSlice2[1] = "test4"

	("dataSlice1:%v %p,dataSlice2:%v %p\n", dataSlice1, dataSlice1, dataSlice2, dataSlice2)
}

func demoData() []string {
	strsPtr := NewString()
	strs := *strsPtr
	defer func() {
		*strsPtr = strs
		PutString(strsPtr)
	}()

	strs = append(strs, "test1", "test2")
	return strs
}

Print result: dataSlice1:[test1 test4] 0xc0000a6400,dataSlice2:[test1 test4] 0xc0000a6400

You can see that the two slice addresses are the same, and the array of the same address is used internally, resulting in the data obtained twice affecting each other.

3. Solution 1

func Test_Pool(t *) {
	dataSlice1 := demoData()
	dataSlice2 := demoData()
	dataSlice2[1] = "test4"

	("dataSlice1:%v %p,dataSlice2:%v %p\n", dataSlice1, dataSlice1, dataSlice2, dataSlice2)
}

func demoData() []string {
	strsPtr := NewString()
	strs := *strsPtr
	defer func() {
		*strsPtr = strs
		PutString(strsPtr)
	}()

	strs = append(strs, "test1", "test2")

	// Deep copy	var items = make([]string, len(strs))
	copy(items, strs)

	return items
}

Use deep copy to copy and return the data before put back, but the resource pool loses its meaning, and after obtaining the resource, a memory application is made.

4. Solution 2

Let's see how golang language source code solves

Refer to go/src/fmt/ 302 lines Fprintln method

func Fprintln(w , a ...any) (n int, err error) {
	p := newPrinter()
	(a)
	n, err = ()
	()
	return
}

You can see that there is () code in 306 lines, and data processing is performed between newPrinter() and free(). After the data processing is completed, the resource will be returned to

Summarize

Not all scenarios are suitable for use, and it is necessary to pay attention to the impact of data synchronization modification in resource pools under concurrency.

This is the end of this article about solving golang pointer data coverage problem. For more related golang pointer coverage content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!