Home > Backend Development > Golang > Why Does Go Return a 'local import in non-local package' Error, and How Can It Be Resolved?

Why Does Go Return a 'local import in non-local package' Error, and How Can It Be Resolved?

Patricia Arquette
Release: 2024-12-13 19:34:23
Original
309 people have browsed it

Why Does Go Return a

Local Import in Go Package

In Go, the import statement is used to import packages. Packages are used to organize code into logical units. When importing a package, you can use a local import or a non-local import.

A local import imports a package from the current working directory. A non-local import imports a package from another directory.

The Error

The following is a file structure:

.
├── bin
│   └── hello
├── pkg
└── src
    └── jacob.uk.com
        ├── greeting
        │   └── greeting.go
        └── helloworld.go
Copy after login

with the following GOPATH:

/Users/clarkj84/Desktop/LearningGo
Copy after login

If you execute the following command within the src folder:

/usr/local/go/bin/go install jacob.uk.com
Copy after login

you will get the following error:

local import "./greeting" in non-local package
Copy after login

This error occurs because you are using a local import in a non-local package.

The Solution

To fix this error, you can change the working directory to src/jacob.uk.com and then execute go install without specifying the package. If you have a helloworld.go file with the following content:

package main

import "./greeting"

func main() {

}
Copy after login

you will get a compile error stating "imported and not used." Once you use something from the imported greeting package, it should compile.

However, it is not recommended to use local imports. Instead, you should use the following import statement:

import "jacob.uk.com/greeting"
Copy after login

By using this import statement, you will be able to compile, run, and install your code from anywhere.

The above is the detailed content of Why Does Go Return a 'local import in non-local package' Error, and How Can It Be Resolved?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template