是否可以在新
类型的声明中包含值。
type Vertex struct {
X, Y int
}
func main() {
v := new( Vertex{ 0, 0} ) // Like so
fmt.Println( v )
// Instead of :
v = new(Vertex)
v.X, v.Y = 12, 4 // extra line for initializing the values of X and Y
fmt.Println( v )
}
或者因为 go 使“Vertex{val, val}”成为文字值而不是基本的 Vertex 类型,所以这是不可能的?
最佳答案
你实际上不需要“new”,你可以简单地写:
v := Vertex{1,2}
如果您想要一个所有成员都设置为其类型的零值的结构(例如,0
对于整数,nil
用于指针,""
用于字符串等),它甚至更简单:
v := Vertex{} // same as Vertex{0,0}
您也可以只初始化一些成员,而将其他成员保留为零值:
v := Vertex{Y:1} // same as Vertex{0,1}
请注意,对于这些 v 将是 Vertex 类型的变量。如果您想要一个指向顶点的指针,请使用:
v := &Vertex{1,2}
关于go - 在新声明中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23349613/