我是一位經驗豐富的“老派”程序員,但也是 Go 的初學者。我正在閱讀“CreateSpace:Go 編程簡介”一書。在第。111,第9章的第三章習題,任務是給用戶自定義的Shape接口添加一個新的方法。界面已經在本章的過程中建立起來了,這是我目前所擁有的:package mainimport ( "fmt" "math")type Shape interface { area() float64 perimeter() float64}type Distance struct { x1, y1, x2, y2 float64}func (d *Distance) distance() float64 { a := d.x2 - d.x1 b := d.y2 - d.y1 return math.Sqrt(a*a + b*b)}type Rectangle struct { x1, y1, x2, y2 float64}func (r *Rectangle) area() float64 { l := distance(r.x1, r.y1, r.x2, r.y1) w := distance(r.x1, r.y1, r.x1, r.y2) return l * w}type Circle struct { x, y, r float64}func (c *Circle) area() float64 { return math.Pi * c.r * c.r}type Perimeter struct { x1, y1, x2, y2 float64}func (p *Perimeter) perimeter() float64 { s1 := distance(p.x1, p.y1, p.x1, p.y2) s2 := distance(p.x1, p.y2, p.x2, p.y2) s3 := distance(p.x2, p.y2, p.x2, p.y1) s4 := distance(p.x2, p.y1, p.x1, p.y1) return s1 + s2 + s3 + s4}func main() { d := new(Distance) d.x2, d.y2, d.x1, d.y1 = 0, 0, 10, 10 p := new(Perimeter) p.x1, p.y1 = 0, 0 p.x2, p.y2 = 10, 10 fmt.Println(p.perimeter()) r := new(Rectangle) r.x1, r.y1 = 0, 0 r.x2, r.y2 = 10, 10 fmt.Println(r.area()) c := Circle{0, 0, 5} fmt.Println(c.area())}問題是我收到以下錯誤(來自編譯器?):user@pc /c/Go/src/golang-book/chapter9/chapterProblems$ go run interface.go# command-line-arguments.\interface.go:25: undefined: distance.\interface.go:26: undefined: distance.\interface.go:42: undefined: distance.\interface.go:43: undefined: distance.\interface.go:44: undefined: distance.\interface.go:45: undefined: distance我花了很多時間重新閱讀章節文本并仔細思考這個“未定義:距離”錯誤可能意味著什么,但到目前為止無濟于事。正如你所看到的,我已經定義了一個“距離結構”,創建了一個名為 的 new() 實例,d用.運算符初始化了它的字段,并創建了一個distance()func,但是,很明顯,我不是在探索一些相關的部分) 的信息。
查看完整描述