go - 在新声明中设置值

标签 go

是否可以在 类型的声明中包含值。

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/

相关文章:

go - 如何将时区设置为现有时间戳而不重新解释它?

Golang - Visual Studio Code 中的本地导入警告

go - 为什么这个程序中存在竞争条件?

go - 跨平台AES CryptLib

mysql - Go Template 循环(范围)出评论

go - 在 Go 中读取不断增长的 mmap 文件

正则表达式替换 Traefik 给出 404

git - "go get"私有(private)存储库的正确方法是什么?

performance - 计数 byte slice 中所有非零字节的最快方法是什么

elasticsearch - 如何使用 go 在 Elasticsearch 中按嵌套对象对文档进行排序?