Exercise 1: Print a Message in Go

Write a program that prints a message to the console.

Why Learn Printing in Go?

Printing text to the console is one of the most fundamental operations in any programming language. In Go, we use the fmt package to handle formatted output. Mastering fmt.Println will help you debug your programs and display information effectively.

Before You Start: Install Go

If you haven't installed Go yet, you need to do so before continuing.

Follow the official installation guide: Install Go

Instructions:

  • 1️⃣ Choose a folder to store your Go project (e.g., GoProjects/MyFirstProject).
  • 2️⃣ Create a file named main.go in this folder.
  • 3️⃣ Open main.go with your preferred editor:
    • ✔️ VS Code (recommended with the Go extension)
    • ✔️ GoLand (paid but powerful)
    • ✔️ Vim / Neovim (for terminal lovers)
    • ✔️ LiteIDE (lightweight IDE for Go)

🚀 Once your editor is ready, you're all set to code! 😃

package main

import "fmt"

func main() {
    fmt.Println("Welcome to the world of Go!")
}
  • 4️⃣ Run the program using the command: go run main.go

Understanding the Code:

1️⃣ package main: Every Go program starts with a package definition. The main package is required to run a standalone program.

2️⃣ import "fmt": Imports the fmt package, which allows printing text to the console.

3️⃣ func main() { ... }: This is the main function, which runs when the program starts.

4️⃣ fmt.Println("Welcome to the world of Go!"): Prints a message to the console.

Other Printing Methods in Go

Besides fmt.Println, Go offers other ways to print text:

  • fmt.Print("Hello") → Prints without a newline.
  • fmt.Printf("Hello, %s!", "Go") → Uses formatted output.

Common Mistakes and How to Fix Them

  • fmt.Println(Welcome to Go!) → Missing double quotes around the string.
  • fmt.PrintLn("Hello") → Incorrect capitalization; should be Println.

Frequently Asked Questions (FAQ)

Q: What is the difference between Print and Println?

A: Print prints text without a newline, whereas Println adds a newline at the end.

Q: How can I format output in Go?

A: Use fmt.Printf for formatted text, such as fmt.Printf("Hello, %s!", "Go").

Learn More About the "fmt" Package

The fmt package is one of the most essential libraries in Go for handling input and output. If you want to explore more about fmt and other must-know Go packages, check out this article.

Read the Full Article →
Next Exercise →

🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee