Merge pull request #257 from PeterBocan/master
Added a constructor to structs
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
49cad39331ee5e9fb8d8dad99d3aff7f18a4e6d0
|
||||
XMZpGsF4sWM
|
||||
cd504951e9f8504c159a66714b04bfda0629e58c
|
||||
ezfE4eojTS7
|
||||
|
||||
@@ -6,3 +6,4 @@ $ go run structs.go
|
||||
Sean
|
||||
50
|
||||
51
|
||||
&{Jon 42}
|
||||
Reference in New Issue
Block a user