Substrings and Go Garbage Collector

Go substitution does not have new memory in Go. Instead, the main representation of the substring contains a data pointer, which is the offset of the original data pointer string.

This means that if I have a large string and you want to track a small substring, the garbage collector will not be able to free any large string until I release all references to the shorter substring.

Slices have a similar problem, but you can work around this by making a copy of the sneak using copy (). I do not know about any similar copy operation for strings. What is the idiomatic and fastest way to make a "copy" of a substring?

+6
source share
1 answer

For instance,

package main import ( "fmt" "unsafe" ) type String struct { str *byte len int } func main() { str := "abc" substr := string([]byte(str[1:])) fmt.Println(str, substr) fmt.Println(*(*String)(unsafe.Pointer(&str)), *(*String)(unsafe.Pointer(&substr))) } 

Output:

 abc bc {0x4c0640 3} {0xc21000c940 2} 
+1
source

Source: https://habr.com/ru/post/946465/


All Articles