我在Go代码示例中注意到初始化struct类型变量的两种样式,但我不明白何时使用它们。
风格1:
package main
import (
"fmt"
)
type Msg struct {
value string
}
func NewMsg(value string) (Msg) {
return Msg{value}
}
func main() {
fmt.Println("Hello, playground")
var helloMsg Msg
helloMsg = NewMsg("oi")
fmt.Println("Hello, ", helloMsg.value)
}风格2:
package main
import (
"fmt"
)
type Msg struct {
value string
}
func NewMsg(value string) (Msg) {
return Msg{value}
}
func main() {
fmt.Println("Hello, playground")
var helloMsg Msg
{
helloMsg = NewMsg("oi")
}
fmt.Println("Hello, ", helloMsg.value)
}第一种风格是一个简单的变量初始化,但第二种方式对我来说更加模糊。花括号是干什么用的?我为什么要用第二种形式?
编辑:
有关这个问题的更多上下文,请参阅Go Kit库的示例代码:https://github.com/go-kit/kit/blob/master/examples/profilesvc/cmd/profilesvc/main.go
发布于 2019-01-31 11:51:42
发布于 2019-02-01 02:07:33
我看不出这两种风格有什么区别。他们完全一样。
{} --它定义了作用域代码,并且在其中声明的一些变量只能在该作用域内使用。但是,如果您在外部声明helloMsg,并在{}块中执行=。“helloMsg”还没有确定范围。
因此,这两种格式的样式完全相同。
https://stackoverflow.com/questions/54459877
复制相似问题