英文:
Import local package
问题
你可以尝试使用相对路径来导入user.go
文件。在main.go
中,你可以使用以下导入语句:
import "./models"
这将导入位于同一目录下的models
包,从而使你能够在main.go
中使用User
结构体。
英文:
My project structure looks like this:
--/project
----main.go
----/models
------user.go
In main.go I want to user user.go:
user.go:
package models
type User struct {
Name string
}
main.go:
package main
import (...)
func main() {
user := &User{Name: "Igor"}
}
How do I import user.go from main.go?
/project is under GOPATH, so I tried:
import "project/models"
but that does nothing.
答案1
得分: 7
你的设置是正确的,但你使用了错误的包。
将代码中的:
user := &User{Name: "Igor"}
改为:
user := &models.User{Name: "Igor"}
或者,如果你不想每次都写 models.XXX,可以将导入语句改为:
import . "project/models"
我发现这样做会使代码在长期内变得更难阅读。对于读者来说,"models.User" 的来源是显而易见的,但对于一个简单的 "User" 来说,通常意味着它来自于当前包。
英文:
Your setup is right, you are using the package wrong.
change:
user := &User{Name: "Igor"}
to:
user := &models.User{Name: "Igor"}
or if you don't want to always say models.XXX, change your import to be.
import . "project/models"
I do find that doing this makes the code a bit harder to read, long term.
It's obvious to the reader where "models.User" comes from, not so much with a plain "User" as normally that means it comes from this package.
答案2
得分: 2
如果您在Go工作区之外构建项目,可以使用相对导入:
import "./models"
然而,使用相对导入并不是一个好主意。首选的方式是导入完整的包路径(并将您的项目放在正确的Go工作区中):
import "github.com/igor/myproject/models"
英文:
If you are building the project outside of a go workspace you can use relative imports:
import "./models"
However, using relative imports is not good idea. The preferred way is to import the full package path (and putting your project in a proper go workspace):
import "github.com/igor/myproject/models"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论