From 5d7a4fd53b37560e9ef496dd6ad3edc873ce7480 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Wed, 24 Oct 2012 09:45:33 -0400 Subject: [PATCH] publish structs --- examples.txt | 2 +- examples/pointers/pointers.go | 4 ++-- examples/structs/structs.go | 39 ++++++++++++++++++++++++----------- examples/structs/structs.sh | 7 +++++++ 4 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 examples/structs/structs.sh diff --git a/examples.txt b/examples.txt index 719586c..8a0f8cc 100644 --- a/examples.txt +++ b/examples.txt @@ -15,7 +15,7 @@ Variadic Functions Closures Recursion Pointers -# Structs +Structs # Methods # Embedding # Interfaces diff --git a/examples/pointers/pointers.go b/examples/pointers/pointers.go index 28b86f2..bb64a38 100644 --- a/examples/pointers/pointers.go +++ b/examples/pointers/pointers.go @@ -37,6 +37,6 @@ func main() { zeroptr(&i) fmt.Println("zeroptr:", i) - // Pointers can be printed too. - fmt.Println("pointer:", &i) + // Pointers can be printed too. + fmt.Println("pointer:", &i) } diff --git a/examples/structs/structs.go b/examples/structs/structs.go index c197e31..05abd7a 100644 --- a/examples/structs/structs.go +++ b/examples/structs/structs.go @@ -1,22 +1,37 @@ +// Go's _structs_ are typed collections of fields. +// They're useful for grouping data together to form +// records. + package main import "fmt" -type Circle struct { - x, y, r float64 +// This `person` struct type has `name` and `age` fields. +type person struct { + name string + age int } func main() { - cEmptyPtr := new(Circle) - fmt.Println(cEmptyPtr) - fmt.Println(*cEmptyPtr) - cValue := Circle{x: 1, y: 2, r: 5} - fmt.Println(&cValue) - fmt.Println(cValue) + // This syntax creates a new struct. + fmt.Println(person{"Bob", 20}) - cOrdered := Circle{1, 2, 5} - fmt.Println(cOrdered) + // You can name the fields when initializing a struct. + fmt.Println(person{name: "Alice", age: 30}) + + // Omitted fields will be zero-valued. + fmt.Println(person{name: "Fred"}) + + // An `&` prefix yields a pointer to the struct. + fmt.Println(&person{name: "Ann", age: 40}) + + // Access struct fields with a dot. + s := person{name: "Sean", age: 50} + fmt.Println(s.name) + + // You can also use dots with struct pointers - the + // pointer will be automatically dereferenced. + sp := &s + fmt.Println(sp.age) } - -// todo: add field access diff --git a/examples/structs/structs.sh b/examples/structs/structs.sh new file mode 100644 index 0000000..85385eb --- /dev/null +++ b/examples/structs/structs.sh @@ -0,0 +1,7 @@ +$ go run structs.go +{Bob 20} +{Alice 30} +{Fred 0} +&{Ann 40} +Sean +50