首页 > 解决方案 > Calling init function from another function

问题描述

why i can't call init function from the other function, init() is just function right, why i can't just call the init function, should i change golang RFC to make it happend

package main

import (
    "fmt"
)

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

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

error :

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

标签: gorfc

解决方案


Go 编程语言规范

包初始化

init 标识符只能用于声明 init 函数,但不声明标识符本身。因此,不能从程序中的任何地方引用 init 函数。


为了实现你的目标,调用一个函数。

例如,

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")

推荐阅读