Added a constructor to structs
This commit is contained in:
@@ -12,6 +12,16 @@ type person struct {
|
||||
age int
|
||||
}
|
||||
|
||||
// A de facto constructor of type `person`.
|
||||
func NewPerson(name string) *person {
|
||||
|
||||
// You can safely return a pointer to local variable
|
||||
// as a local variable will survive the scope of the function.
|
||||
p := person{name: name}
|
||||
p.age = 42
|
||||
return &p
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
// This syntax creates a new struct.
|
||||
@@ -38,4 +48,7 @@ func main() {
|
||||
// Structs are mutable.
|
||||
sp.age = 51
|
||||
fmt.Println(sp.age)
|
||||
|
||||
// Call our constructor
|
||||
fmt.Println(NewPerson("Jon"))
|
||||
}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0
|
||||
XMZpGsF4sWM
|
||||
71e8ecdcf8c8fbddbb250ada5bbe8659b68d5229
|
||||
nHvnHAGTYHq
|
||||
|
||||
@@ -6,3 +6,4 @@ $ go run structs.go
|
||||
Sean
|
||||
50
|
||||
51
|
||||
&{Jon 42}
|
||||
Reference in New Issue
Block a user