英文:
imported and not used error
问题
我无法弄清楚如何创建一个包并使用它。我正在使用liteid和go 1.4.2,但这一切都可以通过命令行重现。我似乎能够创建shape包,但它无法从主包中加载。
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 -> 生成shape.a
go build packages.go
# packages
d:\src\teaching\golang\src\packages\packages.go:5: 导入的包未使用: "shape"
d:\src\teaching\golang\src\packages\packages.go:8: 未定义: Shape
d:\src\teaching\golang\src\packages\packages.go:19: 未定义: 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))
}
有什么想法吗?
英文:
I can't figure out how to create a package and use it. I'm using liteid and go 1.4.2 but this is all reproduce-able from the command-line. I' able to create the shape package it seems but it doesn't load from the main package.
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))
}
Any ideas?
答案1
得分: 9
Shape
在 shape 包中定义。你需要将其引用为 shape.Shape
。
英文:
Shape
is defined in the shape package. You have to reference it as shape.Shape
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论