BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Hello World

Go 1.23

Your first Go program - the traditional starting point for learning any programming language. This code sample demonstrates the basic structure of a Go application, including the package declaration, import statement, and the main function entry point. It serves as a fundamental introduction to Go's syntax and executable structure.

Code

package main

import "fmt"

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

Explanation

This is the quintessential first program in any programming language. In Go, every executable program must belong to the main package and contain exactly one main function, which serves as the program's entry point. When you run a Go program, the Go runtime automatically calls the main function first.

The package declaration is mandatory as the first line of every Go source file. Using package main specifically tells the Go compiler to create an executable binary file. If you used any other package name (like package utils), Go would treat this as a reusable library package that can be imported by other programs, rather than a standalone executable.

The fmt package is part of Go's extensive standard library and provides formatted I/O functions similar to C's printf and scanf. The Println function formats output using default formats, automatically adds spaces between operands, and crucially appends a newline character at the end—making each call print on a new line.

Key characteristics of Go's program structure:

  • Package declaration must be the first line in every source file
  • The main function takes no arguments and returns no values
  • Go source files are UTF-8 encoded by default
  • Imports must be used—unused imports cause compilation errors

Code Breakdown

1
The package declaration must be the first line of every Go file. "package main" indicates this is an executable program. If you used any other package name (like "package mylib"), Go would treat this as a library package that can be imported by other programs, not as a standalone executable.
3
The import statement brings in the fmt (format) package from Go's standard library. This package provides I/O functions for formatting and printing. You can import multiple packages by using parentheses: import ( "fmt" "os" ).
5-7
This defines the main function, which is the entry point of the program. When you run a Go executable, the runtime calls this function first. Inside, we call fmt.Println which prints the string "Hello, World!" to standard output and adds a newline at the end.