diff --git a/examples/structs/structs.go b/examples/structs/structs.go index 6cf5629..384b57c 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -12,6 +12,15 @@ type person struct { age int } +// NewPerson constructs a new person struct with the given name +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. @@ -26,6 +35,9 @@ func main() { // An `&` prefix yields a pointer to the struct. fmt.Println(&person{name: "Ann", age: 40}) + // It's idiomatic to encapsulate new struct creation in constructor functions + fmt.Println(NewPerson("Jon")) + // Access struct fields with a dot. s := person{name: "Sean", age: 50} fmt.Println(s.name) diff --git a/examples/structs/structs.hash b/examples/structs/structs.hash index 2c0e37f..50e4d67 100644 --- a/examples/structs/structs.hash +++ b/examples/structs/structs.hash @@ -1,2 +1,2 @@ -49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0 -XMZpGsF4sWM +cd504951e9f8504c159a66714b04bfda0629e58c +ezfE4eojTS7 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 ac4a3cb..0ca3b3e 100644 --- a/public/structs +++ b/public/structs @@ -43,7 +43,7 @@ records.
package main
@@ -80,6 +80,36 @@ records.
NewPerson constructs a new person struct with the given name
+ +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
+}
+
It’s idiomatic to encapsulate new struct creation in constructor functions
+ + fmt.Println(NewPerson("Jon"))
+
Access struct fields with a dot.
@@ -178,11 +221,22 @@ pointers are automatically dereferenced.Structs are mutable.
sp.age = 51
fmt.Println(sp.age)
-}
+
}