【问题标题】:GoLang: Use internal package [duplicate]GoLang:使用内部包[重复]
【发布时间】:2022-06-11 00:17:36
【问题描述】:

我在尝试使用内部包时遇到问题。

这是我的项目结构:

.
├── go.mod
├── main.go
└── services
    └── business.go

services/business.go 是:

package services

import (
    "math"
)

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * math.Pow(c.Radius, 2)
}

type Square struct {
    Width  float64
    Height float64
}

func (s Square) Area() float64 {
    return s.Width * s.Height
}

type Sizer interface {
    Area() float64
}

我正在尝试使用 main.go 中的服务包:

package main

import "fmt"
import "./services"

func main() {
    fmt.Printf("Hello World, %s.\n", "Jordi")

    c := Circle{Radius: 10}
    s := Square{Height: 10, Width: 5}

    l := Less(c, s)
    fmt.Printf("%+v is the smallest\n", l)
}

func Less(s1, s2 Sizer) Sizer {
    if s1.Area() < s2.Area() {
        return s1
    }
    return s2
}

目前,我得到:

无法导入服务(不需要模块提供包“服务”)

之后,我尝试执行:go get ./services,但问题一直失败。

有什么想法吗?

编辑

我的模块是:

module me/jeusdi/goplay

go 1.18

我试过了:

import "me/jeusdi/goplay/services"

不过,我现在收到了这条消息:

“me/jeusdi/goplay/services”已导入但未用作服务

【问题讨论】:

标签: go


【解决方案1】:

你能试试下面的代码吗?我已经复制了你的代码,它没有任何问题。

我相信您已经在 main.go 中导入了服务包,但您没有使用它。你必须使用它,比如services.Circle。此外,如果您使用的是 VS 代码,它会自动进行导入。

程序结构:

├── go.mod
├── main.go
└── services
    └── business.go

go.mod:

module me/jeusdi/goplay

go 1.18

ma​​in.go

package main

import (
    "fmt"
    "me/jeusdi/goplay/services"
)

func main() {
    fmt.Printf("Hello World, %s.\n", "Jordi")


    c := services.Circle{Radius: 10}
    s := services.Square{Height: 10, Width: 5}

    l := Less(c, s)
    fmt.Printf("%+v is the smallest\n", l)
}

func Less(s1, s2 services.Sizer) services.Sizer {
    if s1.Area() < s2.Area() {
        return s1
    }
    return s2
}

services/business.go

package services

import (
    "math"
)

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * math.Pow(c.Radius, 2)
}

type Square struct {
    Width  float64
    Height float64
}

func (s Square) Area() float64 {
    return s.Width * s.Height
}

type Sizer interface {
    Area() float64
}

输出:

go run main.go 
Hello World, Jordi.
{Width:5 Height:10} is the smallest

【讨论】:

    【解决方案2】:

    这里go get 不是必需的。您需要在此处使用您的模块名称。喜欢

    import "mymodule/services"
    

    假设你的 go.mod 包含

    module mymodule
    
    go 1.x
    ...
    

    【讨论】:

    • 我已经尝试过你的方法,但我遇到了其他问题。我在帖子中添加了其他详细信息...
    猜你喜欢
    • 2015-09-03
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2017-07-16
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多