go - 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
解决方案
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")
推荐阅读
- android - 我的 Android Studio 不断与 RecyclerView (Kotlin) 崩溃
- java - 为什么我的模拟代码调用真实代码?
- azure-active-directory - 使用 OAuth2 的 Exchange Web 服务和更新用户日历
- architecture - UML 和 OCL 的区别
- inno-setup - 在 InnoSetup 脚本的设置部分中找不到文件
- java - 加载二维板
- wordpress - 关键字的Wordpress简码?
- javascript - setTimeout & onload 有问题
- python - pybind11 - 将 STL 容器 std::list 变成不透明类型?
- javascript - 为什么 Context 为父组件返回 undefined 而不是它的子组件?