init() Function क्या है
In this page:
func init() {
// runs automatically before main
}
Defining init()
बिना parameters या return values वाला init नाम का एक function इसके package के initialize होते ही अपने आप चलता है, program के main() function शुरू होने से पहले -- आप इसे कभी explicitly खुद call नहीं करते।
उदाहरण: Defining init()
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// Define the function init
func init() {
// Print the values followed by a newline
fmt.Println("init runs first")
}
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println("main runs second")
}
Login to try C/C++/Java/PHP code in the editor
Multiple init() Functions
एक single package में कई init() functions हो सकते हैं, यहां तक कि एक file के अंदर कई, और Go main शुरू होने से पहले उन्हें उनके दिखने के order में चलाता है (files में, filename order में)।
उदाहरण: Multiple init() Functions
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// Define the function init
func init() {
// Print the values followed by a newline
fmt.Println("first init")
}
// Define the function init
func init() {
// Print the values followed by a newline
fmt.Println("second init")
}
// main is where the program starts running
func main() {
fmt.Println("main")
}
Login to try C/C++/Java/PHP code in the editor
Common Uses for init()
init() आमतौर पर एक-बार के setup के लिए उपयोग होता है जो किसी भी दूसरे code से पहले होना चाहिए, जैसे ज़रूरी configuration validate करना या किसी shared registry में कुछ register करना, क्योंकि यह main से पहले चलने की गारंटी रखता है।
उदाहरण: Common Uses for init()
package main
import "fmt"
var validConfig bool
func init() {
validConfig = true // pretend this checked real configuration
}
func main() {
fmt.Println("config valid:", validConfig)
}
Login to try C/C++/Java/PHP code in the editor
- अलग files में कई init() functions के execution order पर Go के file-name-based ordering rules को समझे बिना भरोसा करना।
- init() को complex application logic के लिए उपयोग करना जो एक explicit, callable setup function के रूप में ज़्यादा साफ़ होता।
- यह भूल जाना कि किसी package के कई init() functions हो सकते हैं (एक file में भी कई), जो सभी अपने आप चलते हैं।
- func init() किसी package के load होने पर अपने आप चलता है, main() शुरू होने से पहले।
- कोई package कई init() functions define कर सकता है, यहां तक कि एक ही file में कई।
- init() कोई arguments नहीं लेता और कोई values return नहीं करता -- इसे explicitly call नहीं किया जा सकता।
- यह आमतौर पर drivers register करने या configuration validate करने जैसे एक-बार के setup के लिए उपयोग होता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: