अपने खुद के Packages बनाना
// myapp/util/util.go
package util
func Exported() {}
// main.go
import "myapp/util"
util.Exported()
Creating a Package Directory
एक reusable package बनाने के लिए, एक नई subdirectory बनाएं और इसके अंदर की हर .go file को एक जैसी package declaration दें, directory के मकसद से मेल खाती -- उदाहरण के लिए 'package mathutils' रखने वाला एक mathutils folder।
उदाहरण: Creating a Package 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("myapp/mathutils/add.go declares: package mathutils")
}
Login to try C/C++/Java/PHP code in the editor
Exporting Identifiers
किसी package में सिर्फ capitalized function, type, और variable नाम इसे import करने वाले code को दिखाई देते हैं -- lowercase identifiers private implementation details बने रहते हैं, package के बाहर अदृश्य।
उदाहरण: Exporting Identifiers
package main
import "fmt"
// Simulating what would live in a separate mathutils package file:
// func Add(a, b int) int { return a + b } -- exported, usable elsewhere
// func subtractInternal(a, b int) int { ... } -- unexported, package-private
func Add(a, b int) int {
return a + b
}
func main() {
fmt.Println(Add(3, 4))
}
Login to try C/C++/Java/PHP code in the editor
Importing Your Own Package
आपकी लिखी एक package उसी तरह import होती है जैसे किसी third-party वाली, module के नाम (go.mod में) plus इसकी subdirectory से बने इसके पूरे path का उपयोग करते हुए, जैसे github.com/example/myapp/mathutils।
उदाहरण: Importing Your Own 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("import \"github.com/example/myapp/mathutils\"")
// Print the values followed by a newline
fmt.Println("then call: mathutils.Add(3, 4)")
}
Login to try C/C++/Java/PHP code in the editor
- किसी ऐसे identifier को capitalize करना भूल जाना जो दूसरे packages से उपयोग होने योग्य होना चाहिए था, इसे अनजाने में private छोड़ते हुए।
- util या common जैसे अत्यधिक generic नाम वाला package बनाना जो असंबंधित code के लिए एक dumping ground बन जाता है।
- module root के सापेक्ष गलत directory में package code रखना, इसके expected import path को तोड़ते हुए।
- एक custom package main के अलावा बस एक package name share करती .go files की एक directory है।
- Package को go.mod में declared इसके module root के सापेक्ष इसके path का उपयोग करके import किया जाता है।
- Exported identifiers (capitalized) दूसरे code को उपयोग करने के लिए package का public API बन जाते हैं।
- अच्छी तरह designed packages की एक छोटी, केंद्रित responsibility होती है बजाय catch-all होने के।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: