How to import local packages in go?

WBOY
Release: 2024-02-11 14:27:08
forward
940 people have browsed it

How to import local packages in go?

In the Go language, you can import local packages by using relative or absolute paths. First, make sure that your local package has a directory structure organized according to the Go language specifications. Then, in your Go file, use the import keyword to import the path to the package. When importing local packages, you can use relative or absolute paths. If your packages are in the same directory, you can use relative paths to import them, such as import "./utils". If your package is in a different directory, you can use an absolute path to import it, such as import "github.com/username/package/utils". In this way, you can successfully import the local package and use its functions and variables.

Question content

I'm new here and working on a sample code that I want to localize.

In the original main.go import statement it is:

import (
    "log"
    "net/http"
    "github.com/foo/bar/myapp/common"
    "github.com/foo/bar/myapp/routers"
)
Copy after login

Now I have common and routers packages in /home/me/go/src/myapp

So I converted the import statement to:

import (
    "log"
    "net/http"
    "./common"
    "./routers"
)
Copy after login

But when I run go install myapp I get the following error:

can't load package: /home/me/go/src/myapp/main.go:7:3: local import "./common" in non-local package
Copy after login

Also, when I use common and routers instead of ./common and ./routers in the import statement, I get:

myapp/main.go:7:3: cannot find package "common" in any of:
    /usr/local/go/src/common (from $GOROOT)
    /home/me/go/src/common (from $GOPATH)
myapp/main.go:8:2: cannot find package "routers" in any of:
    /usr/local/go/src/routers (from $GOROOT)
    /home/me/go/src/routers (from $GOPATH)
Copy after login

How can I solve this problem?

Solution

Well, I solved the problem. Basically the starting path for Go import is $HOME/go/src

So I only need to add myapp in front of the package name, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)
Copy after login

The above is the detailed content of How to import local packages in go?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!