Write a program that prints a message to the console.
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.
If you haven't installed Go yet, you need to do so before continuing.
Follow the official installation guide: Install Go
GoProjects/MyFirstProject
).main.go
in this folder.main.go
with your preferred editor:🚀 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!")
}
go run main.go
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.
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.fmt.Println(Welcome to Go!)
→ Missing double quotes around the string.fmt.PrintLn("Hello")
→ Incorrect capitalization; should be Println
.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")
.
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.
🚀 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! ☕😊