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

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

问题描述



  func a()string {
/ *无关紧要* /
}

b * string =& a()

这会产生错误:

lockquote

无法取得()


的地址

我的理解是,如果Go的地址被占用,Go会自动将一个局部变量提升到堆中。这里清楚的是返回值的地址是要被采用的。

解决方案

地址运算符返回一个指向具有home的东西的指针,例如,一个变量。代码中表达式的值是无家可归。如果你真的需要一个*字符串,你必须分两步来完成:

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

请注意,尽管* string有完全有效的用例,使用它们是一个错误。在Go string 中是一个值类型,但它是一个便宜的类型(一个指针和一个int)。字符串的是不可变的,改变了 * string 变化的地方,而不是字符串值,所以在大多数情况下 * string 根本不需要。


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

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

b *string = &a()

This generates the error:

cannot take the address of a()

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?

解决方案

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

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天全站免登陆