从另一个函数调用 init 函数

Calling init function from another function

为什么我不能从另一个函数调用 init 函数,init() 是正确的函数,为什么我不能只调用 init 函数,我应该改变吗golang RFC 让它发生

package main

import (
    "fmt"
)

func init() {
    fmt.Println("Hello, playground")
}

func main() {
    go init()
    fmt.Println("Hello, playground")
}

错误:

./prog.go:12:8: undefined: init

The Go Programming Language Specification

Package initialization

the init identifier can be used only to declare init functions, yet the identifier itself is not declared. Thus init functions cannot be referred to from anywhere in a program.


要完成您的 objective,请调用函数。

例如,

package main

import (
    "fmt"
)

func init() {
    f("init")
}

func f(s string) {
    fmt.Printf("f(%q)\n", s)
}

func main() {
    f("main")
}

游乐场:https://play.golang.org/p/isyrCIeYCV4

输出:

f("init")
f("main")

init 无法调用,它会在加载包时运行。

package main

import (
    "fmt"
)

func init() {
    fmt.Println("Hello, playground")
}
func main(){
}

结果:你好,操场