-
먼저, propagandist 패키지를 수정하여 init() 함수를 포함해 보겠습니다. propagandist.go를 업데이트합니다:
package propagandist
import "fmt"
var Shout = "I Love LabEx" // Public variable
var secret = "I love the dress" // Private variable
var initialized bool
func init() {
fmt.Println("Initializing propagandist package...")
initialized = true
}
func Hit() string {
return "Don't hit me, please!"
}
func IsInitialized() bool {
return initialized
}
-
이제, propagandist 패키지에 여러 init() 함수를 보여주기 위해 다른 파일을 만들어 보겠습니다:
touch ~/project/propagandist/second.go
파일에 다음 내용을 추가합니다:
package propagandist
import "fmt"
func init() {
fmt.Println("Second init function in propagandist package...")
}
-
초기화 순서를 보여주기 위해 새로운 helper 패키지를 생성합니다:
mkdir -p ~/project/helper
touch ~/project/helper/helper.go
파일에 다음 내용을 추가합니다:
package helper
import "fmt"
var Message = "Helper package is ready"
func init() {
fmt.Println("Initializing helper package...")
}
func GetMessage() string {
return Message
}
-
helper 패키지에 대한 모듈 파일을 추가합니다:
cd ~/project/helper
go mod init helper
-
pacExercise.go를 업데이트하여 두 패키지를 모두 사용하고 초기화 순서를 보여줍니다:
package main
import (
"fmt"
"helper"
"propagandist"
)
func init() {
fmt.Println("Initializing main package...")
}
func main() {
fmt.Println("Main function is running")
fmt.Println(propagandist.Shout)
fmt.Println(helper.Message)
fmt.Printf("Propagandist initialized: %v\n", propagandist.IsInitialized())
}
-
main 프로젝트의 go.mod 파일을 업데이트하여 로컬 helper 패키지를 포함합니다:
cd ~/project
echo "replace helper => ./helper" >> go.mod
go mod tidy
-
프로그램을 실행하고 초기화 순서를 관찰합니다:
go run pacExercise.go
예상 출력 (두 propagandist init 함수의 정확한 순서는 다를 수 있습니다):
Initializing helper package...
Initializing propagandist package...
Second init function in propagandist package...
Initializing main package...
Main function is running
I Love LabEx
Helper package is ready
Propagandist initialized: true
이 초기화 시퀀스는 Go 패키지를 설계할 때, 특히 종속성을 관리하거나 특정 순서로 발생해야 하는 설정 작업을 수행할 때 중요한 고려 사항입니다.