Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
apxp Avatar asked May 16 '19 19:05

apxp


Video Answer


1 Answers

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

like image 110
apxp Avatar answered Oct 11 '22 14:10

apxp