gogo-playground

How can I define different files or packages inside the Go playground?


How can I define different files or packages inside the Go playground?

Specially for checking it can be handy to define a package inside the playground. But to manage this I need to define different files. How can I manage this?


Solution

  • The playground supports now different files. To define a file you need to write:

    -- path/to/file.go --
    package myPackage
    
    // ...
    -- foo/foo.go --
    /*
    Package foo defines Bar() for showing how
    multiple files can be used inside the playground
    */
    package foo
    
    import "fmt"
    
    func Bar() {
        fmt.Println("The Go playground now has support for multiple files!")
    }
    

    To call your package you need to import that package. Therefore you need to define a Go module inside a separate go.mod file.

    -- go.mod --
    module play.ground
    

    Now you can import your package you defined inside the playground:

    package main
    
    import "play.ground/foo"
    
    func main() {
        foo.Bar()
    }
    

    Putting everything together: https://play.golang.org/p/KLZR7NlVZNX