Golang中如何导入自己的模块

Golang中如何导入自己的模块 我知道这是一个非常基础的问题,但我正在努力完成教程《从另一个模块调用你的代码 - Go 编程语言》。我的目录结构如下:

  • Go
    • greetings
    • hello

在 greetings 目录下有 greetings.go 文件:

package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

以及对应的 go.mod 文件。 在 hello 目录下有 hello.go 文件:

package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

所有这些都遵循教程。然而,当我尝试编译 hello 模块时,出现以下错误:

example.com/hello imports
	example.com/greetings: cannot find module providing package example.com/greetings: unrecognized import path "example.com/greetings": reading https://example.com/greetings?go-get=1: 404 Not Found

有人能告诉我我做错了什么吗?非常感谢!


更多关于Golang中如何导入自己的模块的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你创建了 mod 文件吗?

go mod init example.com
go mod tidy

更多关于Golang中如何导入自己的模块的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


感谢您的回答。是的,我做了。

greetings 必须是 main 所在文件夹的子文件夹。main 必须与 go.mod 文件位于同一文件夹中,所有这些在官方文档中都有详细说明。

问题出在你的 go.mod 文件配置上。example.com 是一个保留域名,Go 工具会尝试从网络获取这个模块。你需要修改模块路径,使用本地路径或版本控制仓库路径。

以下是解决方案:

1. 修改 greetings 模块的 go.mod 文件

greetings 目录中,将 go.mod 文件中的模块路径改为本地路径:

module example.com/greetings

go 1.21

改为:

module greetings

go 1.21

或者使用相对路径:

module ../greetings

go 1.21

2. 修改 hello 模块的 go.mod 文件

hello 目录中,使用 replace 指令指向本地 greetings 模块:

module example.com/hello

go 1.21

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0

或者直接修改导入路径:

module hello

go 1.21

require greetings v0.0.0

replace greetings => ../greetings

同时修改 hello.go 中的导入语句:

package main

import (
    "fmt"
    "greetings"
)

func main() {
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

3. 完整示例

目录结构:

Go/
├── greetings/
│   ├── go.mod
│   └── greetings.go
└── hello/
    ├── go.mod
    └── hello.go

greetings/go.mod:

module greetings

go 1.21

hello/go.mod:

module hello

go 1.21

replace greetings => ../greetings

require greetings v0.0.0

hello/hello.go:

package main

import (
    "fmt"
    "greetings"
)

func main() {
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

4. 执行步骤

hello 目录中运行:

go mod tidy
go run hello.go

输出应该是:

Hi, Gladys. Welcome!

如果你使用的是 Go 1.18+,还可以使用工作区模式:

Go 目录下创建 go.work 文件:

go 1.21

use (
    ./greetings
    ./hello
)

然后在 hello 目录中直接运行:

go run hello.go

这样就不需要在 go.mod 中使用 replace 指令了。

回到顶部