2 回答

TA貢獻1982條經驗 獲得超2個贊
使用 Area 方法的接口切片:
shapes := []interface{ Area() float64 }{Rect{5.0, 4.0}, Circle{5.0}}
for _, shape := range shapes {
fmt.Printf("Area of %T = %0.2f\n", shape, shape.Area())
}

TA貢獻1818條經驗 獲得超11個贊
這實際上是兩個問題:如何創建接口,以及如何同時運行一些東西。
定義接口很簡單:
type Shape interface {
Area() float64
}
由于 Go 的魔力,每個Area() float64定義了函數的類型都會自動實現這個接口。
多虧了這個接口,我們可以將多個形狀放入一個切片中:
shapes := []Shape{
Rect{5.0, 4.0},
Circle{5.0},
}
循環這個很容易:
for _, shape := range shapes {
// Do something with shape
}
同時打印該區域確實不是您想要做的事情。它提供了不可預測的輸出,其中多行可能混合在一起。但是讓我們假設我們同時計算這些區域,然后在最后打印它們:
areas := make(chan float64)
for _, shape := range shapes {
currentShape := shape
go func() { areas <- currentShape.Area() }()
}
for i := 0; i < len(shapes); i++ {
fmt.Printf("Area of shape = %0.2f\n", <-areas)
}
注意我們必須如何currentShape在循環內捕獲局部變量,以避免它在 goroutine 有機會運行之前改變 goroutine 內的值。
還要注意我們如何不使用for area := range areas來消耗通道。這將導致死鎖,因為在將所有區域寫入通道后通道并未關閉。還有其他(也許更優雅)的方法來解決這個問題。
- 2 回答
- 0 關注
- 95 瀏覽
添加回答
舉報