Struct

  1. type Circle struct {
  2. Origin, Radius float32
  3. }
  4. func (c *Circle) Area() float32 {
  5. return math.Pi * c.Radius * c.Radius
  6. }

Pointer

  1. c := Circle{0.0, 1.0}
  2. pc := &c
  3. pc := &Circle{0.0, 1.0}

Interface

基本用法

  1. type Task interface {
  2. Do() error
  3. }
  4. type IntTask int
  5. func (i IntTask) Do() error {
  6. if i > 0 {
  7. return nil
  8. }
  9. return errors.New("negative int value")
  10. }

嵌套接口

  1. type Reader interface {
  2. Read(p []byte) (n int, err error)
  3. }
  4. type Writer interface {
  5. Write(p []byte) (n int, err error)
  6. }
  7. type ReadWriter interface {
  8. Reader
  9. Writer
  10. }

并发

go

  1. for i := 0; i < 4; i++ {
  2. go func(v int) {
  3. fmt.Println("v=", v)
  4. }(i)
  5. }

channel

  1. ch := make(chan int) // create a channel of type int
  2. ch <- 42 // Send a value to the channel ch.
  3. v := <-ch // Receive a value from ch
  4. // Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
  5. ch := make(chan int, 100)
  6. close(ch) // closes the channel (only sender should close)
  7. // read from channel and test if it has been closed
  8. v, ok := <-ch
  9. // if ok is false, channel has been closed
  10. // Read from channel until it is closed
  11. for i := range ch {
  12. fmt.Println(i)
  13. }
  • 向 nil channel 发送,会阻塞
  1. var c chan int
  2. c <- 0
  3. // fatal error: all goroutines are asleep - deadlock!
  • 从 nil channel 读取,阻塞
  1. var c chan int
  2. <-c
  3. // fatal error: all goroutines are asleep - deadlock!
  4. // if in select, just ignore the nil channel
  5. package main
  6. import (
  7. "fmt"
  8. "time"
  9. )
  10. func main() {
  11. var c chan int
  12. d := make(chan int)
  13. go func() {
  14. select {
  15. case <-c:
  16. fmt.Println("No way")
  17. case <-d:
  18. fmt.Println("Received!")
  19. }
  20. }()
  21. time.Sleep(1 * time.Second)
  22. d <- 0
  23. time.Sleep(1 * time.Second)
  24. fmt.Println("ok")
  25. }
  26. // Received
  27. // ok
  • 向已关闭的 channel 发送,会 panic
  1. c := make(chan int)
  2. close(c)
  3. c <- 0
  4. // panic: send on closed channel
  • 从已关闭的 channel 读取,会马上返回 0 值
  1. var c = make(chan int, 2)
  2. c <- 1
  3. c <- 2
  4. close(c)
  5. for i := 0; i < 3; i++ {
  6. fmt.Printf("%d ", <-c)
  7. }
  8. // 1 2 0