当前位置:网站首页>Go language -init() function - package initialization

Go language -init() function - package initialization

2022-06-24 14:21:00 Crying while learning

init Similarities and differences between function and main function

  • init() main() All are go Reserved functions in language . from go Program calls automatically , Cannot be called manually .
  • init() The definition of the function is similar to that of the main function , Parameters cannot have and return values .init() The function executes before the main function executes .
  • init() Functions can be defined in any package , And multiple... Can be defined repeatedly . The main function can only be used in main It's a bag , And only one .
  • One package Can be imported multiple times by other packages , But initialization can only be performed once .

We can define it in the code init() function . This function will execute when the package is imported .

for example . If it's true main Import package from , There is... In the package init() function , that init() The code in will be in main() Execute before function execution , Used to initialize the specific data required by the package .

init() Function execution order

  • In the same package ,init() Function from top to bottom .
  • In the same package Different go In file ,init() The function is based on go Sort the string of file name .
  • Different package in , If we don't depend on each other , according to import Sequential execution init() function .
  • If package There is dependence ,init() The order of function calls is : The last package to be relied on , The first to perform .

原网站

版权声明
本文为[Crying while learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241237270564.html