Sobes.tech
Junior — Middle

Kas saaksite selgitada funktsiooni init() eesmärki programmeerimise kontekstis?

sobes.tech AI

Vastus AI-lt

In the Go language, the init() function is used to initialize a package before the main program executes. It is automatically called once when the package is loaded, before the main() function is invoked.

Purpose of init():

  • Initialize variables, constants, or structures that require complex logic.
  • Configure the package state, such as registering handlers or connecting to resources.

Example:

package main

import "fmt"

var config string

func init() {
    config = "initialized"
    fmt.Println("init called")
}

func main() {
    fmt.Println("main called")
    fmt.Println("config:", config)
}

The output will be:

init called
main called
config: initialized

This way, init() helps prepare the environment before the main program logic starts.