ProgramGuru

Basic Go Programs

Start with Basic Go Programs

Learn basic go programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of basic go programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Practice short complete programs before combining larger features. A typical beginner exercise declares variables, computes a result, and displays it with fmt.

Values in these introductory examples are defined in code so readers can run them in an online compiler without interactive input.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example basicSmall programs make language rules easy to test.Set variablesStep 1Calculate resultsStep 2Print valuesStep 3Change inputsStep 4Small programs make language rules easy to test.
Small programs make language rules easy to test.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	first, second := 12, 8
	fmt.Println("First:", first)
	fmt.Println("Second:", second)
	fmt.Println("Sum:", first+second)
	fmt.Println("Difference:", first-second)
}

Output

First: 12
Second: 8
Sum: 20
Difference: 4

Trace what the program does

The first two lines display assigned variables. Addition and subtraction produce 20 and 4, respectively.

Avoid common mistakes

  • Use := only when declaring a new variable in a function.
  • Do not assume an uninitialized variable is undefined: Go supplies a zero value.

Try it yourself

Add multiplication and a carefully chosen integer-division example.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does := do inside a function?
Choose one answer. You can try again.

Answer and explanation

Declare and initialize a variable

Correct. The first two lines display assigned variables.

What you should remember

You have practiced Basic Go Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Number Programs →