导入本地包

huangapple go评论68阅读模式
英文:

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"

huangapple
  • 本文由 发表于 2015年5月4日 02:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/30017777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定