douzhuo2002 2017-12-14 11:17
浏览 117
已采纳

如何在GO中导入本地包

I am creating a web API.

I built my server and controller in the same file main.go.

I created another file name model.go where I declare a Person struct.

I can't export my model in main.go.

Every time I run or build I get this error :

can't load package: package .: found packages main 

Is there a way to export func/const and import them in file with good path? (Like the way JavaScript works).

This is my tree:

myapp/
  --main.go/
  --model.go/

This is my import: main.go

package main

import (
   "encoding/json"
   "log"
   "net/http"

   "./person"
   "github.com/gorilla/mux"
)

model.go

package person

type Person struct {
   ID        string   `json:"id,omitempty"`
   Firstname string   `json:"firstname,omitempty"`
   Lastname  string   `json:"lastname,omitempty"`
   Address   *Address `json:"address,omitempty"`
}

var people []Person
  • 写回答

1条回答 默认 最新

  • dsg41888 2017-12-14 12:11
    关注

    within the same folder you must have the same package name.

    When golang processes imports it loads all files under the same directory as a whole.

    given the code you presented, model.go package name must be main.

    You simply don t need to import model.go from main.go.

    Now, there s a little thing to know about. When you will run go build/run/install, it will take the list of files passed as parameters to initialize the build process.

    In your current setup that means you must pass all files composing the main package to the command line, otherwise, they will be ignored, in your case that means a build failure.

    In plain text, you will do go build *.go instead of go build main.go

    In the future if you want to avoid multiple source files to build, you should have a unique main.go, with the minimum code in it to initialize the program you are writing. As a consequence the content of model.go will exist within a different package (directory), and will be imported into main via an import xyz statement.

    Finally, import path of the import directives must not be relative to the current working directory. They are all GOPATH/src based.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分