Why do we need init function

in init function i can declare some usefull variables but

func init() {
 var Hello string = "Hello World"
}

func main() {
  fmt.Println(Hello)
}

gives an error, so why do we need init() and how to use it for what purposes?

You should be declaring Hello in the global scope if you want to use it in main().

var Hello string

func init() {
    Hello = "Hello World"
}

func main() {
    fmt.Println(Hello)
}

Here’s a direct quote from the official Golang site:

Besides initializations that cannot be expressed as declarations, a common use of init functions is to verify or repair correctness of the program state before real execution begins.

1 Like

the answer to why we need or rather use init() is when we require something to be run just one time with in the
runtime while at the same time having all of the code with in main() function running repeatedly or seperatly.

in case of web dev, is it a good place to fetch data from api ?

If you want a solid example of the usage of init() in web development, check this out from the Golang Blog repo on Github. And while you’re at it, check out the entire project! It’s made by the creators of Go, so it should good.

They are using init that way because golang/blog is deployed on AppEngine which requires all handlers to be declared in init(). This should not be taken as a general example of usage of init() in web development. It is very specific to AppEngine.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.