Go中的临时地址? [英] Address of a temporary in Go?

查看:20
本文介绍了Go中的临时地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理这种情况的最干净的方法是什么:

What's the cleanest way to handle a case such as this:

func a() string {
    /* doesn't matter */
}

b *string = &a()

这会产生错误:

不能取a()的地址

我的理解是,如果获取了地址,Go 会自动将局部变量提升到堆中.这里很清楚,要取返回值的地址.处理这个问题的惯用方法是什么?

My understanding is that Go automatically promotes a local variable to the heap if its address is taken. Here it's clear that the address of the return value is to be taken. What's an idiomatic way to handle this?

推荐答案

地址操作符返回一个指针,指向具有家"的东西,例如.一个变量.您的代码中表达式的值是无家可归".如果你真的需要一个 *string,你必须分两步完成:

The address operator returns a pointer to something having a "home", e.g. a variable. The value of the expression in your code is "homeless". if you really need a *string, you'll have to do it in 2 steps:

tmp := a(); b := &tmp

请注意,虽然 *string 有完全有效的用例,但很多时候使用它们是错误的.在 Go 中,string 是一种值类型,但传递起来很便宜(一个指针和一个 int).字符串的是不可变的,改变一个*string会改变home"指向的位置,而不是字符串值,所以在大多数情况下*string根本不需要.

Note that while there are completely valid use cases for *string, many times it's a mistake to use them. In Go string is a value type, but a cheap one to pass around (a pointer and an int). String's value is immutable, changing a *string changes where the "home" points to, not the string value, so in most cases *string is not needed at all.

这篇关于Go中的临时地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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