For the question of the best solution for your situation, walking around “static” lines
- Pass a string type instead of * string.
- Do not make assumptions about what is going on behind the scenes.
It is tempting to give advice “don't worry about the distribution of strings”, because this is really the case when you describe where the same string is transmitted, possibly many times. Although it's generally good to think about memory usage. It is simply very difficult to guess, and even worse to guess, based on experience with another language.
Here is a modified version of your program. Where do you assume memory is allocated?
package main import "fmt" var konnichiwa = `こんにちは世界` func test1() *string { s := `Hello world` return &s } func test2() string { return `Hej världen` } func test3() string { return konnichiwa } func main() { fmt.Println(*test1()) fmt.Println(test2()) fmt.Println(test3()) }
Now ask the compiler:
> go tool 6g -S t.go
(I called the program t.go.). Outputting results for calls to runtime.new. There is only one! I spoil it for you, this is in test1.
Therefore, without stopping at too much touch, a small look at the compiler’s output indicates that we avoid selection by working with a string type and not with a * string.
Sonia source share