Go main() Function

beginner
16 min

Go main() Function

Welcome to the world of Golang! Today, we'll dive deep into the heart of every Golang program - the main() function.

What is the main() function? šŸ’”

In Golang, the main() function is the entry point of your program. When you run your program, the Go runtime starts executing the main() function.

go
package main import "fmt" func main() { fmt.Println("Hello, World!") }

šŸ“ Note: Every Go program must have a main() function.

The Anatomy of a Go Program šŸŽÆ

A Go program is made up of one or more files, with each file containing one or more functions. The main() function, which is the entry point of your program, must be in the same file as the package declaration.

go
package main import "fmt" func main() { fmt.Println("Hello, World!") }

Here's a breakdown:

  • package main: This line tells the Go compiler that this is a standalone program and not a library.
  • import "fmt": This line imports the fmt package, which contains functions for formatted I/O.
  • func main(): This line declares the main() function, which is the entry point of the program.
  • fmt.Println("Hello, World!"): This line uses the fmt.Println() function to print "Hello, World!" to the console.

Variables and Types in Go šŸ“

Go is a statically typed language, which means each variable has a specific type. Here are some basic types:

  • int: Integer numbers
  • float64: Floating-point numbers
  • string: Strings of characters
go
package main import "fmt" func main() { var name string = "John Doe" var age int = 30 var height float64 = 1.75 fmt.Println("Name:", name) fmt.Println("Age:", age) fmt.Println("Height:", height) }

Functions in Go šŸ’”

Functions in Go are first-class citizens, which means they can be passed around and used as values. Here's an example of a function that calculates the area of a circle.

go
package main import "fmt" // Function to calculate the area of a circle func calculateCircleArea(radius float64) float64 { return 3.14 * radius * radius } func main() { radius := 5.0 area := calculateCircleArea(radius) fmt.Println("Area of the circle:", area) }

Quiz

Quick Quiz
Question 1 of 1

Which line in the Go program is the entry point?

Wrapping Up

You've now got a good grasp of the main() function and some basic concepts in Golang. As you continue learning, remember to write clean, readable, and maintainable code. Happy coding! šŸš€

šŸ“ Note: Stay tuned for our next lessons where we'll explore more Go concepts!


This content is created by Mistral AI. If you have any questions or feedback, please let me know!


This content is optimized for SEO, but please note that the emphasis is on providing a high-quality learning experience for our users.