| -- Hello.Play -- |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| fmt.Println("Hello, world!") |
| } |
| -- Hello.Output -- |
| Hello, world! |
| -- Import.Play -- |
| package main |
| |
| import ( |
| "fmt" |
| "log" |
| "os/exec" |
| ) |
| |
| func main() { |
| out, err := exec.Command("date").Output() |
| if err != nil { |
| log.Fatal(err) |
| } |
| fmt.Printf("The date is %s\n", out) |
| } |
| -- KeyValue.Play -- |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| v := struct { |
| a string |
| b int |
| }{ |
| a: "A", |
| b: 1, |
| } |
| fmt.Print(v) |
| } |
| -- KeyValueImport.Play -- |
| package main |
| |
| import ( |
| "flag" |
| "fmt" |
| ) |
| |
| func main() { |
| f := flag.Flag{ |
| Name: "play", |
| } |
| fmt.Print(f) |
| } |
| -- KeyValue.Output -- |
| a: "A", b: 1 |
| -- KeyValueImport.Output -- |
| Name: "play" |
| -- KeyValueTopDecl.Play -- |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| var keyValueTopDecl = struct { |
| a string |
| b int |
| }{ |
| a: "B", |
| b: 2, |
| } |
| |
| func main() { |
| fmt.Print(keyValueTopDecl) |
| } |
| -- KeyValueTopDecl.Output -- |
| a: "B", b: 2 |
| -- Sort.Play -- |
| package main |
| |
| import ( |
| "fmt" |
| "sort" |
| ) |
| |
| // Person represents a person by name and age. |
| type Person struct { |
| Name string |
| Age int |
| } |
| |
| // String returns a string representation of the Person. |
| func (p Person) String() string { |
| return fmt.Sprintf("%s: %d", p.Name, p.Age) |
| } |
| |
| // ByAge implements sort.Interface for []Person based on |
| // the Age field. |
| type ByAge []Person |
| |
| // Len returns the number of elements in ByAge. |
| func (a ByAge) Len() int { return len(a) } |
| |
| // Swap swaps the elements in ByAge. |
| func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age } |
| |
| // people is the array of Person |
| var people = []Person{ |
| {"Bob", 31}, |
| {"John", 42}, |
| {"Michael", 17}, |
| {"Jenny", 26}, |
| } |
| |
| func main() { |
| fmt.Println(people) |
| sort.Sort(ByAge(people)) |
| fmt.Println(people) |
| } |
| -- Sort.Output -- |
| [Bob: 31 John: 42 Michael: 17 Jenny: 26] |
| [Michael: 17 Jenny: 26 Bob: 31 John: 42] |