在Go中引用字符串文字 [英] Reference to string literals in Go

查看:136
本文介绍了在Go中引用字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我将经常传递对静态字符串的引用.我希望避免让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.

为什么不能获取字符串文字的地址(请参见下面的示例中的test1())?我是否误解了语法,还是由于Go的内部工作而造成的限制?

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()可以工作,但是每次都会为var hej分配内存吗?
test3()不会分配任何新的内存,但是我希望避免该函数之外的混乱情况.

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

感谢帮助!

推荐答案

获取文字(字符串,数字等)的地址是非法的,因为它的语义不明确.

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?

test2的情况下,不存在这种歧义,因为您正在处理的语义已明确定义的现有变量.如果将字符串定义为const,则不会起作用.

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.

语言规范通过明确不允许您的要求来避免这种歧义.解决方法是test2.虽然稍微冗长一些,但它使规则保持简洁明了.

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.

当然,每个规则都有其例外,在Go中,这涉及到复合文字:以下内容合法,并在规范中进行了定义:

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

这篇关于在Go中引用字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆