How to add multiple packages in a Go REPL?
Hey everyone, new to go.
I'm having a hard time trying the packages concept I just learned.
This is the file structure I'm having:
main.go games/ maps.go
maps.go
package games func PlayAGame(){}
main.go
package main import ( "fmt" "games" )
I'm trying to import the games package in main.go but I'm not able to.
So wanted to know whether packages don't work in repl here?
Thanks a lot.
As of 2022 with go 1.16.7 in Repl.it, both methods (bfs999 and
HackermonDev) don't seem to work.
One way worked for me is the following...
In the file structure like this:
-root(.) ---main.go ---go.mod -----mypkg -------my_pkg.go -------go.mod
where ./mypkg/my_pkg.go
has
package mypkg ...
and ./mypkg/go.mod
is needed with the following content to indicate the package mypkg
to Go:
module mypkg go 1.16
In the UI, modify the go.mod
in the Packager Files section to the following (it is actually located at ./go.mod
):
module main go 1.16 replace mypkg v0.0.0 => ./mypkg require mypkg v0.0.0 // indirect
The replace
directive will translate mypkg
in the import line to the correct local package directory (./mypkg
).
In main.go
, you can now import the package using import "mypkg"
and use the package like mypkg.
.
This does appear to be supported now, and since I spent a long time looking for it, I figured I'd share. Thanks to @GrahamWalters on https://repl.it/talk/ask/How-to-import-local-packages-in-go/21017.
In a file structure such as this
-root ---main.go ---pkg ------pkg.go
the local package (pkg in this case) can be accessed in main through
package main import ( "main/pkg" ) func main() { pkg.SomeFunc() }
I'm pretty sure you have to put "./games"