diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 6cf5629..21584a2 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -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")) } diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 2c0e37f..a1194e9 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0 -XMZpGsF4sWM +71e8ecdcf8c8fbddbb250ada5bbe8659b68d5229 +nHvnHAGTYHq diff --git a/examples/structs/structs.sh b/examples/structs/structs.sh index 6d82fa0..f0d6025 100644 --- a/examples/structs/structs.sh +++ b/examples/structs/structs.sh @@ -6,3 +6,4 @@ $ go run structs.go Sean 50 51 +&{Jon 42} \ No newline at end of file diff --git a/public/structs b/public/structs index 31c03d0..22fd85f 100644 --- a/public/structs +++ b/public/structs @@ -29,7 +29,7 @@ records.
package main
@@ -66,6 +66,36 @@ records.
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
+}
+
Structs are mutable.
sp.age = 51
fmt.Println(sp.age)
+
Call our constructor
+ + fmt.Println(NewPerson("Jon"))
}