简体   繁体   English

Go 中的封装使用问题

[英]Problems to use packages in Go

I'm having problems to use packages.我在使用包时遇到问题。 I a following literally the steps I find online, but I have an error message.我确实按照我在网上找到的步骤进行操作,但我收到一条错误消息。

I have this package in GOPATH:我在 GOPATH 中有这个 package:

go/src/greet/day.go去/src/greet/day.go

package greet

var morning = "Good morning"
var Morning = "hey" + morning

I want to import it in my code:我想在我的代码中导入它:

go/src/app/entry.go去/src/app/entry.go

package main

import ("fmt"
        "greet")

func main(){
    fmt.Println(greet.Morning)
}

When I run entry.go, I receive this message: entry.go:4:3: package greet is not in GOROOT (/usr/local/go/src/greet)当我运行 entry.go 时,我收到这条消息: entry.go:4:3: package greet is not in GOROOT (/usrgo/src)

Does anybody how to fix it?有人如何解决它吗?

Thank you.谢谢你。

GOPATH isn't really used anymore. GOPATH 不再被真正使用。 You can use a different directory and run go mod init greet .您可以使用不同的目录并运行go mod init greet This will create a new module "greet" in that folder, and from within that module you can import packages using import "{module name}/{package path}".这将在该文件夹中创建一个新模块“greet”,您可以在该模块中使用 import“{module name}/{package path}”导入包。 It is a best practice to use the folder name as the package name, so the import path matches the folder names (except for main packages).最佳做法是使用文件夹名称作为 package 名称,因此导入路径与文件夹名称匹配(主包除外)。

Additionally, if your module lives in a git repository, your module name should be the path to the git repository.此外,如果您的模块位于 git 存储库中,则您的模块名称应该是 git 存储库的路径。 for example, go mod init github.com/jaenmo/myrepo .例如, go mod init github.com/jaenmo/myrepo

within your module make a folder for your main package.在您的模块中为您的主要 package 创建一个文件夹。 You should be able to import using your module name.您应该能够使用您的模块名称进行导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 GO - 无法导入包 - GO - Could not import packages GO:我如何使用 go 反射来设置结构指针的值 - GO: how can i use go reflect to set the value of pointer of struct 将 AWS Glue Python 与 NumPy 和 Pandas Python 程序包一起使用 - Use AWS Glue Python with NumPy and Pandas Python Packages 如何使用geth提供的go API调用智能合约? - How to use the go API provided by geth to call smart contracts? 如何将 cloud.google.com/go/datastore 与 AppEngine 一起使用? - How to use cloud.google.com/go/datastore with AppEngine? 如何使用 Flutter Firebase 动态链接与 go_router - How to use Flutter Firebase dynamic links with go_router 如何在 Go 测试中使用带有 testify/suite 的自定义标志 - How to use custom flag with testify/suite in Go test 使用 go 和 Vue + Vite 编写的 wasm 函数的设置 - What setup to use wasm functions written in go with Vue + Vite 如果我们想使用 S3 来托管 Python 包,我们如何告诉 pip 在哪里可以找到最新版本? - If we want use S3 to host Python packages, how can we tell pip where to find the newest version? 包裹无法识别 - Packages are not recognized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM