Package के Basics
package name
func Exported() {}
func unexported() {}
Declaring a Package
हर Go source file 'package name' से शुरू होती है, declare करते हुए कि यह किस package से belong करती है। एक directory और package name share करने वाली files एक cohesive unit बनाती हैं जो आपस में unexported identifiers share कर सकती हैं।
उदाहरण: Declaring a Package
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println("this file belongs to package main")
}
Login to try C/C++/Java/PHP code in the editor
One Package Per Directory
एक single directory के अंदर सीधे सभी .go files को एक जैसा package name declare करना चाहिए (external test files के लिए खास _test package suffix के अलावा) -- Go code को individual file से नहीं, directory से organize करता है।
उदाहरण: One Package Per Directory
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println("mathutils/add.go: package mathutils")
// Print the values followed by a newline
fmt.Println("mathutils/subtract.go: package mathutils")
}
Login to try C/C++/Java/PHP code in the editor
package main Is Special
सिर्फ package main, एक func main() के साथ combined, को 'go build' से एक standalone executable में compile किया जा सकता है। हर दूसरा package name एक library produce करता है जिसे import होना है, कभी सीधे चलाना नहीं।
उदाहरण: package main Is Special
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println("Only package main can be built into a runnable binary")
}
Login to try C/C++/Java/PHP code in the editor
- एक ही directory की files में कई अलग package names डालना -- एक directory में हर .go file को एक जैसा package name declare करना चाहिए।
- यह मान लेना कि package name को directory name से बिल्कुल मेल खाना चाहिए -- यह conventional है, लेकिन Go को सिर्फ खुद directory के अंदर consistency चाहिए।
- यह भूल जाना कि package main खास है: सिर्फ यह एक चलने योग्य binary produce कर सकता है, बाकी सब एक library के रूप में build होते हैं।
- हर Go file एक package declaration से शुरू होती है जो इसे एक ही directory में दूसरी files के साथ group करती है।
- एक directory के अंदर सीधे सभी .go files को एक जैसा package name share करना चाहिए।
- package main एक चलने योग्य executable produce करने के लिए reserved है; दूसरे नाम import होने योग्य libraries produce करते हैं।
- Packages Go की code organization और namespacing की unit हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: