publish structs

This commit is contained in:
Mark McGranaghan 2012-10-24 09:45:33 -04:00
parent db2166ca82
commit 5d7a4fd53b
4 changed files with 37 additions and 15 deletions

View File

@ -15,7 +15,7 @@ Variadic Functions
Closures Closures
Recursion Recursion
Pointers Pointers
# Structs Structs
# Methods # Methods
# Embedding # Embedding
# Interfaces # Interfaces

View File

@ -37,6 +37,6 @@ func main() {
zeroptr(&i) zeroptr(&i)
fmt.Println("zeroptr:", i) fmt.Println("zeroptr:", i)
// Pointers can be printed too. // Pointers can be printed too.
fmt.Println("pointer:", &i) fmt.Println("pointer:", &i)
} }

View File

@ -1,22 +1,37 @@
// Go's _structs_ are typed collections of fields.
// They're useful for grouping data together to form
// records.
package main package main
import "fmt" import "fmt"
type Circle struct { // This `person` struct type has `name` and `age` fields.
x, y, r float64 type person struct {
name string
age int
} }
func main() { func main() {
cEmptyPtr := new(Circle)
fmt.Println(cEmptyPtr)
fmt.Println(*cEmptyPtr)
cValue := Circle{x: 1, y: 2, r: 5} // This syntax creates a new struct.
fmt.Println(&cValue) fmt.Println(person{"Bob", 20})
fmt.Println(cValue)
cOrdered := Circle{1, 2, 5} // You can name the fields when initializing a struct.
fmt.Println(cOrdered) 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

View File

@ -0,0 +1,7 @@
$ go run structs.go
{Bob 20}
{Alice 30}
{Fred 0}
&{Ann 40}
Sean
50