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
Recursion
Pointers
# Structs
Structs
# Methods
# Embedding
# Interfaces

View File

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

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

View File

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