'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:
- run
go env -w GO111MODULE=offthengo run main.go, it throwsmain.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) - run
go installin the./mathfolder, nothing happened. - copy
./mathfolder to/usr/local/go/src/chapter11/and rungo run main.goit 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))
}
Solution 1:[1]
It turned out:
- You can create the project on Desktop e.g
/Users/username/Desktop/Learn/learn-go. go installin the project folder e.g/Users/username/Desktop/Learn/learn-gowill create a file on/usr/local/go/bin.- If you create a package e.g
package mathand you wish to access it, you need to run e.ggo mod init example.com/chapter11and then you need to addimport "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 |
