grafov/go-playground

Multi-file support

velppa opened this issue · 1 comments

Go playground has a multi-file support, like https://play.golang.org/p/rq4J90MxTKJ

package main

import (
	"play.ground/foo"
)

func main() {
	foo.Bar()
}

-- go.mod --
module play.ground

-- foo/foo.go --
package foo

import "fmt"

func Bar() {
	fmt.Println("This function lives in an another file!")
}

Is there any way to execute similar snippet in go-playground?

Short answer: yes.
See detailed explanation below.

By default go-playground used for short snippets of the code that placed in a single file with default name snippet.go. But design of go-playground allows to extend it for an abitrary number of files and packages. Especially it is convenient when you use go modules.

The go-playground creates a new directory for a new snippet. For example I just added the new snippet and got:

  /home/a/go/src/playground/at-2022-01-06-192907:
  total 12
  drwxr-xr-x 1 a a   48 jan  6 19:31   .
  drwxr-xr-x 1 a a 4730 jan  6 19:29   ..
  -rw-r--r-- 1 a a   48 jan  6 19:29   go.mod
  -rw-r--r-- 1 a a  357 jan  6 19:29   snippet.go

You could add another files (with find-file) to the same main package. As well as directories with a new packages (with mkdir for example). Here I added "sample" package to the subdirectory:

package sample

var Sample = "sample"

And imported it this way:

package main

import (
	"fmt"

	"playground/at-2022-01-06-192907/sample"
)

func main() {
	fmt.Println("Results:", sample.Sample)
}

Import path looks a bit weird by default. You would change the module name in go.mod. For example I changed it from "playground/at-2022-01-06-192907" to "play":

module play

go 1.17

Then I could import "sample" with shorter new path:

import (
	"fmt"

	"play/sample"
)

func main() {
	fmt.Println("Results:", sample.Sample)
}

Just treat go-playground as a fully functional go project that created with a temporary path. You could clean old snippet directories or keep them for history (removing of old snippets out of scope of go-playground yet). But anyway the created snippets is general Go projects that could set own subpackages or import any external packages.