Welcome to our Go Packages Introduction lesson! In this comprehensive guide, we'll delve into the world of Go packages, a crucial part of the Go programming language. Let's get started!
Go packages are a way to structure and organize Go code into reusable modules. They help manage dependencies and make it easier to share code between different projects. Think of them as a box containing multiple Go source files and executables.
Let's create a simple Go package. In your terminal, create a new directory for your package:
mkdir mypackage
cd mypackageNow, create a new Go file (.go) in this directory:
touch main.goOpen main.go in your favorite text editor and add the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}This simple Go program defines a main function that prints "Hello, World!" when run. Since we didn't specify any package other than main, the entire code belongs to the main package.
To create a sub-package, simply create a new directory within the main package directory and add a .go file inside it. For example:
mkdir subpackage
touch subpackage/sub.goOpen subpackage/sub.go and add the following code:
package subpackage
import "fmt"
func Hello() {
fmt.Println("Hello from subpackage!")
}Now, you can use this sub-package in the main package by importing it in main.go:
package main
import (
"fmt"
"mypackage/subpackage"
)
func main() {
fmt.Println("Hello, World!")
subpackage.Hello()
}When you run this code, it will print "Hello, World!" followed by "Hello from subpackage!".
What is the purpose of Go packages?
Stay tuned for our next lesson, where we'll explore more about working with Go packages, including importing external packages and creating multiple packages in a single project. Happy learning! 🚀