Go Packages Introduction 🎯

beginner
9 min

Go Packages Introduction 🎯

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!

What are Go Packages? 📝

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.

Creating a Simple Package ✅

Let's create a simple Go package. In your terminal, create a new directory for your package:

bash
mkdir mypackage cd mypackage

Now, create a new Go file (.go) in this directory:

bash
touch main.go

Open main.go in your favorite text editor and add the following code:

go
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.

Creating a Sub-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:

bash
mkdir subpackage touch subpackage/sub.go

Open subpackage/sub.go and add the following code:

go
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:

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!".

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🚀