Struct
type Circle struct {
Origin, Radius float32
}
func (c *Circle) Area() float32 {
return math.Pi * c.Radius * c.Radius
}
Pointer
c := Circle{0.0, 1.0}
pc := &c
pc := &Circle{0.0, 1.0}
Interface
基本用法
type Task interface {
Do() error
}
type IntTask int
func (i IntTask) Do() error {
if i > 0 {
return nil
}
return errors.New("negative int value")
}
嵌套接口
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
并发
go
for i := 0; i < 4; i++ {
go func(v int) {
fmt.Println("v=", v)
}(i)
}
channel
ch := make(chan int) // create a channel of type int
ch <- 42 // Send a value to the channel ch.
v := <-ch // Receive a value from ch
// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
ch := make(chan int, 100)
close(ch) // closes the channel (only sender should close)
// read from channel and test if it has been closed
v, ok := <-ch
// if ok is false, channel has been closed
// Read from channel until it is closed
for i := range ch {
fmt.Println(i)
}
var c chan int
c <- 0
// fatal error: all goroutines are asleep - deadlock!
var c chan int
<-c
// fatal error: all goroutines are asleep - deadlock!
// if in select, just ignore the nil channel
package main
import (
"fmt"
"time"
)
func main() {
var c chan int
d := make(chan int)
go func() {
select {
case <-c:
fmt.Println("No way")
case <-d:
fmt.Println("Received!")
}
}()
time.Sleep(1 * time.Second)
d <- 0
time.Sleep(1 * time.Second)
fmt.Println("ok")
}
// Received
// ok
c := make(chan int)
close(c)
c <- 0
// panic: send on closed channel
- 从已关闭的 channel 读取,会马上返回 0 值
var c = make(chan int, 2)
c <- 1
c <- 2
close(c)
for i := 0; i < 3; i++ {
fmt.Printf("%d ", <-c)
}
// 1 2 0