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
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.