Added a constructor to structs

This commit is contained in:
PeterBocan
2019-07-01 16:45:01 +02:00
parent 46fe6bc6cb
commit c127e2898e
4 changed files with 61 additions and 4 deletions

View File

@@ -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"))
}

View File

@@ -1,2 +1,2 @@
49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0
XMZpGsF4sWM
71e8ecdcf8c8fbddbb250ada5bbe8659b68d5229
nHvnHAGTYHq

View File

@@ -6,3 +6,4 @@ $ go run structs.go
Sean
50
51
&{Jon 42}