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 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备