go語言中import不允許迴圈包含

李維發表於2019-02-16

go的包不允許迴圈包含,具體例子:

main.go:

package main

import (
    "fmt"
    "test/pkg1"
)

func main() {
    fmt.Println("in main.main")
    fmt.Printf("pkg1.Black=%s
", pkg1.Black)
    fmt.Printf("pkg2.Black=%s
", pkg2.Black)
}

func init() {
    fmt.Println("in main.init")
    fmt.Printf("pkg1.Black=%s
", pkg1.Black)
    fmt.Printf("pkg2.Black=%s
", pkg2.Black)
}

pkg1.go:

package pkg1

import (
    "fmt"
    "test/pkg2"
)

const (
    Black string = "#000"
    white string = "#fff"
)

func init() {
    fmt.Println("in pkg1.init")
    fmt.Printf("pkg2.Black=%s
", pkg2.Black)
}

pkg2.go:

package pkg2

import (
    "fmt"
    "test/pkg1"
)

const (
    Black string = "#000"
    white string = "#fff"
)

func init() {
    fmt.Println("in pkg2.init")
    fmt.Printf("pkg1.Black=%s
", pkg1.Black)
}

go build報錯:

import cycle not allowed

相關文章