>  기사  >  백엔드 개발  >  Go 언어의 init 함수에 대한 자세한 설명

Go 언어의 init 함수에 대한 자세한 설명

尚
앞으로
2019-11-30 14:41:123915검색

Go 언어의 init 함수에 대한 자세한 설명

go 언어의 init 함수는 go 언어의 중요한 기능입니다.

1 init 함수는 프로그램 실행 전 패키지에 사용됩니다. 패키지 내 변수 초기화 등의 초기화 함수

2 각 패키지는 여러 개의 init 함수를 가질 수 있습니다.

3 패키지의 각 소스 파일도 여러 개의 init 함수를 가질 수 있습니다.

4 동일한 패키지 내 여러 개의 init가 없습니다. Go 언어의 함수 실행 순서에 대한 명확한 정의(설명)

5 다양한 패키지의 init 함수는 패키지에서 가져온 종속성에 따라 초기화 함수의 실행 순서를 결정합니다

6 init 함수는 호출할 수 없습니다. 다른 함수에서는 실행되기 전에 자동으로 호출됩니다

다음 예제는 "the way to go"에서 발췌한 것입니다. 애플리케이션이 초기화되면 OS 차이점이 숨겨집니다.

var prompt = "Enter a digit, e.g. 3 " + "or %s to quit."

func init() {
    if runtime.GOOS == "windows" {
        prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter")
    } else { // Unix-like
        prompt = fmt.Sprintf(prompt, "Ctrl+D")
    }
}

다음 두 go 파일은 시연합니다. :

1 패키지 또는 go 파일에는 여러 init 함수가 포함될 수 있습니다.

2 init 함수는 기본 함수보다 먼저 실행됩니다.

3 init 함수는 자동으로 호출되며 다른 함수에서는 호출할 수 없습니다. 함수가 정의되지 않았습니다.

gprog .go code

package main

import (
    "fmt"
)

// the other init function in this go source file
func init() {
    fmt.Println("do in init")
}

func main() {
    fmt.Println("do in main")
}

func testf() {
    fmt.Println("do in testf")
    //if uncomment the next statment, then go build give error message : .\gprog.go:19: undefined: init
    //init()
}

ginit1.go 코드, 이 소스 파일에는 두 개의 init 함수가 있습니다.

package main

import (
    "fmt"
)

// the first init function in this go source file
func init() {
    fmt.Println("do in init1")
}

// the second init function in this go source file
func init() {
    fmt.Println("do in init2")
}

위의 두 파일을 컴파일하십시오. go build gprog.go ginit1.go

The show 컴파일 후 gprog.exe를 실행한 결과, gprog.go의 init 함수가 먼저 실행되고 ginit1.go의 두 init 함수가 실행된 다음 main 함수가 실행됩니다.

E:\opensource\go\prj\hellogo>gprog.exe
do in init
do in init1
do in init2
do in main

참고: "the way to go"(P70)에 아래 빨간색 설명이 있습니다. 이는 go 소스 파일이 하나의 init 함수만 가질 수 있음을 의미합니다.

그러나 위의 ginit1.go에 있는 두 개의 init 함수는 컴파일됩니다. 실행 후 모두 정상적으로 실행되었으니

그러므로 이 문장은 사무적인 오류임이 틀림없습니다.

4.4.5 Init-functions
Apart from global declaration with initialization, variables can also be initialized in an init()-function.
This is a special function with the name init() which cannot be called, but is executed automatically
before the main() function in package main or at the start of the import of the package that
contains it.
Every source file can contain only 1 init()-function. Initialization is always single-threaded and
package dependency guarantees correct execution order.

추천:

동영상 튜토리얼

위 내용은 Go 언어의 init 함수에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제