Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created January 18, 2024 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/4fcf0a313ffdbda99c59931b1142e8bb to your computer and use it in GitHub Desktop.
Save Integralist/4fcf0a313ffdbda99c59931b1142e8bb to your computer and use it in GitHub Desktop.
[Golang init] #go #golang
// This is a file designed to be run on go.dev/play (link below).
// It validates the behaviour of init() functions.
// i.e. init() is only called once regardless of how many times its package is imported.
// https://go.dev/play/p/99YpDma6mVJ
package main
import (
"play.ground/bar"
"play.ground/foo"
)
func main() {
foo.Message()
bar.Message()
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
import (
"fmt"
"play.ground/bar"
)
func Message() {
fmt.Println("This is the foo package")
bar.Message()
}
-- bar/bar.go --
package bar
import "fmt"
func init() {
fmt.Println("This is the init() inside the bar package")
}
func Message() {
fmt.Println("This is the bar package")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment