go語言中import不容許循環包含

go的包不容許循環包含,具體例子:ui

main.go:code

package main

import (
    "fmt"
    "test/pkg1"
)

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

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

pkg1.go:string

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\n", pkg2.Black)
}

pkg2.go:it

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\n", pkg1.Black)
}

go build報錯:test

import cycle not allowed
相關文章
相關標籤/搜索