main()
and init
are two functions reserved for special purpose in Go
.
The main
package in the Go
language contains a main
function, which shows that the file is executable. The
main()
is the program’s entry point; we do not need to call it, and no value is passed as an argument or returned from this function.
package mainimport ("fmt""sort")func main() {ele := []int{23,44,2,4,85}sort.Ints(ele)fmt.Println("Sorted elements: ", ele)}
main
.fmt
and sort.
main()
.sort
package to sort it.The init()
function is the same as the main()
function in a way that no value is passed or returned from an init()
function. Every package contains init()
it executes when we initialize a package. It executes before the main()
function and is independent of the main() function. When we cannot initialize the global variables in a global context, we use init()
to initialize it. We do not need to declare the init()
explicitly, and neither can we refer to it anywhere in the program, but we are allowed to create multiple init()
functions; they execute in the order they are created.
package mainimport ("fmt")func init(){fmt.Println("This is the init function")}func main() {fmt.Println("This is the main function")}
init()
function that will execute before main()
.init()
function.