'Is it possible to create package outside of GOROOT or GOPATH? [duplicate]

My goal is to create a Go's project folder on Desktop /Users/username/Desktop/Learn/golang-package and create a math package.

Reference: https://www.golang-book.com/books/intro/11

The problem is: go run main.go throws main.go:4:2: package chapter-11/math is not in GOROOT (/usr/local/go/src/chapter11/math)

What I've did:

  1. run go env -w GO111MODULE=off then go run main.go, it throws
    main.go:4:2: cannot find package "chapter11/math" in any of:
         /usr/local/go/src/chapter11/math (from $GOROOT)
         /Users/username/go/src/chapter11/math (from $GOPATH)
    
  2. run go install in the ./math folder, nothing happened.
  3. copy ./math folder to /usr/local/go/src/chapter11/ and run go run main.go it works but I wish to be able to put it on Desktop instead of /usr/local/go where I need to enter the password every time I need to create a new folder or change the folder name.

The folder overview

golang-package
|-main.go
|-chapter11
  |- math
     |- math.go

main.go

package main

import (
    "chapter11/math"
    "fmt"
)

func main() {
    xs := []float64{1, 2, 3, 4}
    avg := math.Average(xs)
    fmt.Println(avg)
}

math.go

package math

func Average(xs []float64) float64 {
    total := float64(0)
    for _, x := range xs {
        total += x
    }
    return total / float64(len(xs))
}
go


Solution 1:[1]

It turned out:

  1. You can create the project on Desktop e.g /Users/username/Desktop/Learn/learn-go.
  2. go install in the project folder e.g /Users/username/Desktop/Learn/learn-go will create a file on /usr/local/go/bin.
  3. If you create a package e.g package math and you wish to access it, you need to run e.g go mod init example.com/chapter11 and then you need to add import "example.com/chapter11/math"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kidfrom