Declaring and initializing an integer pointer

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年9月20日 08:24:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/32674516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定