Reference to string literals in Go

前端 未结 5 1120
忘了有多久
忘了有多久 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:18

    I am using interface{} to indicate that my string will be sometimes nil. In my case it looks like:

    testCases := []struct {
            Values map[string]interface{}
        }{
            {
                Values: map[string]interface{}{"var1": nil},
            },
            {
                Values: map[string]interface{}{"var1": "my_cool_string"},
            },
        }
    

    And later in following code (You may also want the assertion check):

    if v != nil {
        vv := v.(string)
    }
    

提交回复
热议问题