Backend with Golang

[번역] Init() function

아직개구리 2024. 1. 19. 23:13

출처: https://www.developer.com/languages/inti-function-golang/ 

Take a quick look at the init() function

  • no arguments & return nothing.
  • meant to run before any other piece of code.
  • whenever the init() function is declared in code, Go loads and runs it prior to anything else in the package.
  • have more than one init() function. the order of their declaration matters in the code, execute exactly in that order.
  • never called explicitly. implicitly by the Go runtime.

When is the init() function used for in Go?

  • when finding out the type of operating system currently running before executing our program
  • importing a package 할 때 많이 쓰임. package 가 imported 되었을때, 그 패키지 안에 어떤 함수를 실행하기 전에 random function의 seed value가 initialized되길 바랄 것이다. 이것이 init() 함수를 통해서 이뤄진다. seed는 함수를 실행할때마다 설정되어야 하는 값이 아니라, 한번만 정해지면 되기 때문에, 이런 상황에 init() function이 알맞다고 할 수 있다.
  • 또 다른 예시로 program이 picture를 process할 때, image 파일의 타입이 다양할 수 있는데, main 함수 실행 전에 type 을 알아내어 올바른 방향으로 프로그램이 실행되도록 할 수 있다.

Problems with init()

  • 단일 파일에 선언된 init() 여러개라면 선언된 순서대로 실행된다. 하지만 init()이 여러 파일에 걸쳐 선언된다면, 파일이름의 알파벳 순서로 처리된다. 알파벳때문에 예상하지 못한 문제가 일어날 수도 있으므로 하나의 파일 안에 init() 함수들을 선언하거나, file name이 lexical order 로 이루어지도록 보장하는 방법이 있다.
  • 전역변수를 변경하거나 관리하면 안된다. 전역 변수는 패키지 전체에 직접적인 영향을 미치기 때문이다.