英文:
Declaring and initializing an integer pointer
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对使用Go语言进行开发还很陌生。似乎你可以使用花括号来初始化字典、结构体等等,但是同样的语法不能用于初始化整数(所有标量?)指针。这可能是因为花括号语法似乎只适用于[复合?]类型。
以下代码是无效的,会出现"new(int) is not a type"错误:
package main
import "fmt"
func main() {
var x int = 5
var y *int = new(int){x}
fmt.Println(x)
fmt.Println(y)
}
那么,有没有一种方法可以将一个整数初始化为对另一个变量的引用,还是这必须总是分开进行?
英文:
I'm new to developing in Go. It seems like, though you're able to initialize a dictionary, structure, etc.. with a value (using curly-brackets), the same syntax can not be used to initialize an integer (all scalars?) pointer with a value. It might be because the curly bracket syntax seem to lend itself exclusively to [composite?] types.
Invalid due to "new(int) is not a type" error:
package main
import "fmt"
func main() {
var x int = 5
var y *int = new(int){x}
fmt.Println(x)
fmt.Println(y)
}
So, is there a way to initialize an integer with a reference to another variable, or does this necessarily always have to be separate steps?
答案1
得分: 1
在使用Go语言进行赋值时,不需要冗长的语法。
x := 5
y := &x
在编译时,x
将会被创建并初始化为int
类型,而y
将会是*int
类型。
注意:由于多重赋值被处理为单个表达式,x, y := 5, &x
是不会起作用的。
英文:
There's no need to be verbose in assignments with go.
x := 5
y := &x
x
will be created and initialized as an int
and y
will be *int
upon compilation.
NOTE: Because multiple assignment is processed as a single expression, x, y := 5, &x
will not work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论