Go变量初始化语法
I notice two styles of initializing a struct type variable in Go code examples but I don't understand when to use each.
Style 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)
}
Style 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)
}
The first style is a simples variable initilization but the second is more obscure to me. What the curly braces do? Why should I use the second form?
EDIT:
For more context on the question, it arrised from this sample code of the Go Kit library: https://github.com/go-kit/kit/blob/master/examples/profilesvc/cmd/profilesvc/main.go
在Go代码示例中,我注意到了两种初始化struct类型变量的样式,但是我不知道何时使用每种样式 。 p>
样式1: p>
package main
import(
“ fmt “
)
type Msg结构{
值字符串
}
func NewMsg(值字符串)(Msg){
返回Msg {value}
}
func main(){\ n fmt.Println(“ Hello,Playground”)
var helloMsg Msg
helloMsg = NewMsg(“ oi”)
fmt.Println(“ Hello,”,helloMsg.value)
}
code> pre>
样式2: p>
package main
import(\ n“ fmt”
)
type Msg结构{
值字符串
}
func NewMsg(值字符串)(Msg){
返回Msg {value}
}
func main( ){
fmt.Println(“ Hello,Playground”)
var helloMsg Msg
{
helloMsg = NewMsg(“ oi”)
}
fmt.Println(“ Hello,”, helloMsg.value)
}
code> pre>
第一种样式是简单变量的初始化 但是第二点对我来说比较晦涩。 花括号做什么? 我为什么要使用第二种形式? p>
编辑: strong> p>
有关此问题的更多背景信息,它由此而来 Go Kit库的示例代码: https://github.com/go-kit/kit/blob/master/examples/profilesvc/cmd/profilesvc/main.go p>
div>
What the curly braces do?
They denote a code block. You use code blocks when you want to restrict scope of an identifier (to that block). Here it doesn't make sense, indeed, because you only have one identifier and it's from the outer scope.
Some reading:
I don't see the difference between these two styles. They're totally the same.
{}
this defines scope codes, and some variables declared inside it can only be used inside that scope.
But if you declare helloMsg
outside and do =
inside the {}
block. 'helloMsg' hasn't been scoped.
So, these two formatted style are totally the same.