Home >Backend Development >Golang >Why Am I Getting the 'Package Not in GOROOT' Error in Go, and How Do I Fix It?

Why Am I Getting the 'Package Not in GOROOT' Error in Go, and How Do I Fix It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 05:40:15576browse

Why Am I Getting the

Error "Package Not in GOROOT": Resolving the Issue

When running go run main.go, you may encounter the error, "package package1 is not in GOROOT (/usr/local/go/src/package1)" if the environment variables are improperly configured. To resolve this issue, meticulously follow these steps:

  1. Configure Environment Variables:
    In the bashrc file, set the following environment variables:

    export GO111MODULE=on
    export GOPATH=/mnt/sda1/programming/gopath
    export PATH=$PATH:$GOPATH/bin
    export GOROOT=/usr/local/go
    export PATH=$PATH:$GOROOT/bin
  2. Load bashrc File:
    Load the bashrc file into the terminal using the following command:

    source ~/.bashrc
  3. Create Project Structure:
    Create a main folder and place main.go inside it. Initialize the project with the following command:

    go mod init main

    Create a separate folder for the package (e.g., package1) and place your Go files in it, but do not create a go.mod file in this folder.

  4. Import Package in Main:
    In your main.go, import the package using the following syntax:

    import "main/package1"
    
    y := package1.Struct1{a: 1, b: 2,...}
    z := y.func1()

The above is the detailed content of Why Am I Getting the 'Package Not in GOROOT' Error in Go, and How Do I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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