Reference to string literals in Go

前端 未结 5 1121
忘了有多久
忘了有多久 2021-01-01 15:27

In my application I will frequently pass references to a static string. I wish to avoid having Go allocate memory for each call, but I failed to get the address to my string

5条回答
  •  粉色の甜心
    2021-01-01 16:26

    For the question of the best solution for your situation of passing around "static" strings,

    1. Pass the string type instead of *string.
    2. Don't make assumptions about what is going on behind the scenes.

    It's tempting to give the advice "don't worry about allocating strings" because that's actually true in the case you're describing where the same string is passed around, perhaps many times. It general though, it's really good to think about memory use. It's just really bad to guess, and even worse to guess based on experience with another language.

    Here's a modified version of your program. Where do you guess that 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 named the program t.go.) Search the output for calls to runtime.new. There's only one! I'll spoil it for you, it's in test1.

    So without going off on too much of a tangent, the little look at the compiler output indicates that we avoid allocation by working with the string type rather than *string.

提交回复
热议问题