dpjpo746884 2012-06-18 18:38
浏览 34
已采纳

在Go中引用字符串文字

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 literal.

Why is it not possible to take the address of a string literal (see test1() in the example below)? Have I misunderstood the syntax, or is it a limitation due to the internal workings of Go?

If not possible, what would be the best solution?

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())
}

Thanks for help!

  • 写回答

4条回答 默认 最新

  • douxing6532 2012-06-18 19:03
    关注

    Taking the address of a literal (string, number, etc) is illegal because it has ambiguous semantics.

    Are you taking the address of the actual constant? Which would allow the value to be modified (and could lead to a runtime error) or do you want to allocate a new object, copy the constant over and get the address to the new version?

    This ambiguity does not exist in the case of test2 since you are dealing with an existing variable of which the semantics are clearly defined. The same would not work if the string was defined as const.

    The language spec avoids this ambiguity by explicitly not allowing what you are asking for. The solution is test2. While it is slightly more verbose, it keeps the rules simple and clean.

    Of course, every rule has its exceptions, and in Go this concerns composit literals: The following is legal and defined as such in the spec:

    func f() interface{} {
        return &struct {
            A int
            B int
        }{1, 2} 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路