Hi Daryl,
On Sat, 10 Jul 2021 12:12:41 -0700 (PDT)
Daryl Robert Miller <
dar...@uci.edu> wrote:
> I have created local packages in support of my main golang program;
> it has been challenging to figure out where to put these packages and
> how to import them. Obviously this area of Go has changed over the
> years so some examples out there are just wrong.
The official Go website provides two up-to-date examples on how create
package and to import them,
*
https://golang.org/doc/code
*
https://golang.org/doc/tutorial/create-module
All of them now include creating and using package as part of the Go
module.
> I got things
> working but can find no info on why, so my question is where is an
> explaination of how / why the below works (specifically using "main"
> prefix):
The specification for packages and import can be read on this pages:
*
https://golang.org/ref/spec#Packages,
*
https://golang.org/ref/spec#Import_declarations
>
> go version go1.16.5 darwin/amd64
> Using Visual Studio Code v 1.58.0 on MacOS
>
> *~/go/src/myproject/main.go*
> package main
>
> import "main/mypackage"
>
> func main() {
> mypackage.Dothis()
> }
> ---
>
> *~/go/src/myproject/mypackage/mypackage.go*
> package mypackage
>
> func Dothis() { }
>
>
Assuming that you are not enabling Go module, anything under
"$HOME/go/src/" directory will be considered as importable.
So, if you have "myproject/mypackage", where "myproject" defined as
package "main", then "main/mypackage" is the _import path_ for that
package that can be imported by any Go source code under "$HOME/go/src"
except by the package itself.
--
Shulhan