gpt4 book ai didi

go - Golang 中的调用函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:40 25 4
gpt4 key购买 nike

我有这样一个函数:

var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}

我想在func main()中调用它:

func main(){
init()
}

但它不起作用,并告诉我 init() 未定义。有什么问题?

最佳答案

init函数是Golang中的一个特殊函数。它在第一次加载文件时执行,因此您永远不必直接调用它。

来自官方文档:

Finally, each source file can define its own niladic init function to set up whatever state is required. (Actually each file can have multiple init functions.) And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

关于go - Golang 中的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37673718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com