【问题标题】:imported and not used error导入但未使用错误
【发布时间】:2015-05-18 21:09:33
【问题描述】:

我不知道如何创建一个包并使用它。我正在使用 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))
}

有什么想法吗?

【问题讨论】:

标签: go packages


【解决方案1】:

Shape 在 shape 包中定义。您必须将其引用为shape.Shape

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多