Go Modules और go.mod
In this page:
module module/path
go 1.21
require example.com/pkg v1.2.3
What Is a Module?
एक Go module संबंधित packages का एक collection है जो साथ versioned और distributed होते हैं, एक module path (अक्सर github.com/user/project जैसा एक repository URL) से पहचाने जाते हैं।
Modules Go का dependency management का unit हैं, Node.js में package.json या Rust में Cargo.toml जैसा।
उदाहरण: What Is a Module?
// 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("A module groups packages under one versioned identity")
}
Login to try C/C++/Java/PHP code in the editor
Creating go.mod with go mod init
एक module path के बाद 'go mod init' चलाना current directory में एक go.mod file बनाता है।
यह file module का नाम और इसे चाहिए minimum Go version record करती है, और यह वह anchor बन जाती है जिसके खिलाफ project के अंदर सभी import paths resolve होते हैं।
उदाहरण: Creating go.mod with go mod init
go mod init github.com/example/myapp
⚠️ Run this in your own terminal or Node.js environment.
Reading a go.mod File
एक go.mod file module directive (इसका नाम), एक go directive (minimum Go version), और हर dependency module को उसके exact version के साथ list करने वाला एक require block list करती है। Go tooling इस file को अपने आप पढ़ती है -- आप इसे शायद ही कभी हाथ से edit करते हैं।
उदाहरण: Reading a go.mod File
module github.com/example/myapp
go 1.22
require (
github.com/some/dependency v1.4.0
)
⚠️ Run this in your own terminal or Node.js environment.
Adding Dependencies
जब आपका code किसी ऐसे package को import करता है जो standard library का हिस्सा नहीं, आप इसे 'go get' से fetch और record करते हैं।
यह go.mod को नई requirement के साथ update करता है और go.sum बनाता या update करता है, जो dependencies की छेड़छाड़ न होने की पुष्टि के लिए cryptographic checksums store करता है।
उदाहरण: Adding Dependencies
go get github.com/some/[email protected]
⚠️ Run this in your own terminal or Node.js environment.
- 'go get' उपयोग करने के बजाय हाथ से go.mod edit करके एक dependency जोड़ना, जिससे go.sum out of sync रह जाता है।
- किसी नए project के लिए import statements लिखने से पहले 'go mod init' चलाना भूल जाना, जिससे packages resolve करने के लिए कोई module नहीं होता।
- ऐसा module path चुनना जो यह मेल नहीं खाता कि code असल में कहां hosted है, जिससे अगर module कभी publish हो तो समस्याएं आती हैं।
- 'go mod init <module-path>' एक go.mod file बनाता है, एक directory को Go module में बदलते हुए।
- go.mod module का नाम, Go version, और इसकी dependencies को exact versions के साथ record करता है।
- Modules ने Go projects manage करने के standard तरीके के रूप में पुराने GOPATH workspace system की जगह ली।
- Dependencies एक package import करके और 'go build' या 'go get' चलाकर अपने आप जोड़ी जाती हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: