Func init what's this?

Why do we need func init(){} ?

checked previous related post but still not very clear. for example, here is previous post:

var hello string

func init(){
    hello = "good morning"
}

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

why we just directly set up `hello := “good morning”?

2 Likes

It’s optional. The example is to demonstrate how to perform package initialization using init() function. Just like main(), it is a reserved name.

Normally, we use init() to do critical checking such as dependencies, plugins checking, system requirements, etc. Splitting those codes away from main() make it clear.

You can squeeze everything in main() as well. It’s individual choice.

1 Like

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