在我的应用程序中,我将经常传递对静电字符串的引用.我希望避免让go for each 调用分配内存,但我无法获得字符串文字的地址.
为什么不能采用字符串文字的地址(参见下面示例中的test1()
)?我是误解了语法,还是由于围棋的内部工作方式造成了限制?
如果不可能,最好的解决方案是什么?
test2()
works, but will it allocate memory for the var hej
each time?
test3()
will not allocate any new memory, but I wish to avoid clutter outside the function.
package main
import "fmt"
var konnichiwa = `こんにちは世界`
// Gives the compile error `cannot take the address of "Hello world"`
func test1() (*string) { return &`Hello world` }
// Works fine
func test2() (*string) {
hej := `Hej världen`
return &hej
}
func test3() (*string) { return &konnichiwa }
func main(){
fmt.Println(*test1())
fmt.Println(*test2())
fmt.Println(*test3())
}
谢谢你的帮助!