我无法弄清楚如何创建包并使用它。我使用liteid并转到1.4.2但这可以从命令行重现。我'能够创建它看起来的形状包但它不会从主包中加载。
GOPATH=d:\src\teaching\golang
GOROOT=c:\go
+teaching\golang\pkg
\windows_386
shape.a
\src
\packages
packages.go
\shape
shape.go
go install shape -> generates shape.a
go build packages.go
# packages
d:\src\teaching\golang\src\packages\packages.go:5: imported and not used: "shape"
d:\src\teaching\golang\src\packages\packages.go:8: undefined: Shape
d:\src\teaching\golang\src\packages\packages.go:19: undefined: Circle
shape.go
package shape
import (
"fmt"
)
const (
pi = float64(3.14)
)
type Shape interface {
Area() float64
}
type Circle struct {
x int
y int
radius int
}
func (c *Circle) Area() float64 {
return pi * float64(c.radius*c.radius)
}
func (c Circle) String() string {
return fmt.Sprintf("{x=%d, y=%d, radius=%d}", c.x, c.y, c.radius)
}
packages.go
package main
import (
"fmt"
"shape"
)
func calculateArea(shapes ...Shape) float64 {
sum := float64(0)
for _, v := range shapes {
sum += v.Area()
}
return sum
}
func main() {
circle := Circle{x: 1, y: 2, radius: 2}
fmt.Println(circle, circle.Area(), calculateArea(&circle))
}
有什么想法吗?
答案 0 :(得分:7)
Shape
在形状包中定义。您必须将其引用为shape.Shape