Merge pull request #257 from PeterBocan/master

Added a constructor to structs
This commit is contained in:
Mark McGranaghan
2019-09-01 15:24:11 -07:00
committed by GitHub
4 changed files with 73 additions and 5 deletions

View File

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

View File

@@ -1,2 +1,2 @@
49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0
XMZpGsF4sWM
cd504951e9f8504c159a66714b04bfda0629e58c
ezfE4eojTS7

View File

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