Learn Go · 2/18

Go Fundamentals: Your First Steps into Gopher-land

7 min read

Course: Go

Topic: Go Fundamentals: Your First Steps into Gopher-land 🚀

Welcome to your first adventure in the world of Go! Don't worry, you don't need to know anything about gophers, but you might just become a fan of them by the end of this. This guide will walk you through the absolute essentials to get you started with writing your own Go programs. Let's get to it!


1. Variables: Your Program's Memory Boxes 📦

The Problem: Imagine you're building a simple app to track your daily coffee intake. You drink a coffee, the count goes up. How does the program remember how many coffees you've had? It can't just write it on a sticky note. We need a way to store information that can change.

The Solution: We use variables! A variable is essentially a named box in your computer's memory where you can store a piece of information. You give it a name, and you can look at what's inside or put something new in it.

In Go, there are a couple of ways to create these memory boxes.

The var keyword

The most explicit way to declare a variable is using the var keyword, followed by the name you want to give the variable, and then its data type.

go
package main

import "fmt"

func main() {
    // Declaring a variable to store the number of coffees
    var numberOfCoffees int
    
    // Assigning a value to it
    numberOfCoffees = 2
    
    fmt.Println(numberOfCoffees) // This will print 2
    
    // You can also declare and assign in one line
    var cupsOfWater int = 8
    fmt.Println(cupsOfWater) // This will print 8
}

🤔 Under the Hood: When you declare a variable, Go finds an empty spot in memory, labels it with the name you provided (like numberOfCoffees), and sets it up to only accept the data type you specified (in this case, int for integer).

The Short Declaration Operator :=

Now, Go developers love to be efficient. The var keyword is great, but for a quick declaration and assignment inside a function, there's a cooler, shorter way: the := operator.

This little guy automatically figures out the data type of the variable based on the value you give it.

go
package main

import "fmt"

func main() {
    // Using the short declaration operator
    numberOfLaptops := 1
    
    fmt.Println(numberOfLaptops) // This will print 1
    
    // Let's add another one
    numberOfLaptops = 2
    fmt.Println(numberOfLaptops) // Now it prints 2
}

Industry Practice: Inside functions, you'll almost always see := being used for its brevity and clarity. Use var when you need to declare a variable without initializing it right away, or for package-level variables.


2. Data Types: Primitives and Classification 🏷️

The Problem: Okay, so we have our memory boxes (variables). But what kind of stuff can we put in them? If you're running a cafe, you need to track the customer's name, the price of their latte, and whether their order is ready. These are all different types of information.

The Solution: Go has a set of built-in data types to classify your information. This is great because it prevents you from accidentally trying to do math with someone's name.

Let's look at the most common "primitive" data types you'll use every day.

  • int: Used for whole numbers (integers), both positive and negative. Think of it as counting things: number of users, number of clicks, etc.
    • Example: var userAge int = 30
  • float64: Used for decimal numbers. If you're dealing with money, measurements, or anything that needs precision, this is your go-to.
    • Example: var price float64 = 4.99
  • string: Used for text. Anything enclosed in double quotes "..." is a string.
    • Example: var customerName string = "John Doe"
  • bool: Can only be one of two values: true or false. It's perfect for things that have a simple yes/no or on/off state.
    • Example: var isOrderReady bool = true

Here's a little program putting them all together:

go
package main

import "fmt"

func main() {
    // Our Cafe Order
    customerName := "Alice"      // string
    orderNumber := 12            // int
    price := 5.75                // float64
    isReady := false             // bool
    
    fmt.Println("Customer:", customerName)
    fmt.Println("Order Number:", orderNumber)
    fmt.Println("Price:", price)
    fmt.Println("Is Ready:", isReady)
}

Funny Exaggeration: If you didn't have data types, you might ask your program to "add 5 to the name 'Alice'". Your computer would probably have an existential crisis. Data types are like the traffic lanes of programming; they keep everything flowing smoothly.


3. Constants: Unchangeable Truths 🏛️

The Problem: In our cafe app, let's say the tax rate is always 7%. We could store this in a variable, but what if some part of our code accidentally changes it to 50%? Suddenly, a 5lattecosts5 latte costs 7.50! We need a way to store a value that can never, ever be changed.

The Solution: For these unchangeable truths, we use constants. They are declared like variables, but with the const keyword. Once a value is assigned to a constant, it is set in stone for the entire run of the program.

go
package main

import "fmt"

func main() {
    const taxRate = 0.07 // 7% tax rate
    
    orderTotal := 15.50
    
    taxAmount := orderTotal * taxRate
    
    fmt.Println("Tax Amount:", taxAmount)
    
    // If you try to do this, Go will give you an error!
    // taxRate = 0.08 // cannot assign to taxRate
}

Industry Practice: Constants are fantastic for values that are fundamental to your application's logic, like mathematical constants (Pi), configuration settings (a default port number), or business rules (the tax rate). By convention, their names are often in camelCase just like variables.

Interesting Fact: In Go, constants are very flexible. They are considered "untyped" until they are used in a context that requires a type. This allows you to use a constant like const pi = 3.14 with both float32 and float64 variables without any conversion issues.


4. Basic Input and Output (The fmt package) 💬

The Problem: Our programs are great at storing information and having unchangeable truths. But so far, they're a bit... quiet. They do their work internally, but they don't talk to us. How can we see the results of their calculations or get information from the user?

The Solution: We need a way to handle Input and Output (I/O). In Go, the primary tool for this is the fmt package (short for "format"). We've already been using it with fmt.Println()!

The fmt package is your program's mouth and ears.

fmt.Println() - Speaking in simple sentences.

This is the one you've seen. It prints whatever you give it to the console and then adds a new line at the end. Simple and effective for quick debugging or showing a result.

go
fmt.Println("Hello, Gopher!")
fmt.Println("Your order total is:", 20.50)

fmt.Printf() - Speaking with style.

Sometimes you want more control over how things are printed. Printf (print formatted) lets you create a template string and then plug your variables into it using special "verbs".

  • %v - The value in a default format
  • %s - For strings
  • %d - For integers
  • %f - For floating-point numbers
  • %T - The type of the variable
go
package main

import "fmt"

func main() {
    customer := "Bob"
    quantity := 3
    price := 2.25
    
    fmt.Printf("Hello, %s! Your order of %d items costs $%.2f.\n", customer, quantity, price*float64(quantity))
    // The .2 in %.2f means "print with 2 decimal places".
    // We also add \n at the end to manually add a new line.
}

This will output: Hello, Bob! Your order of 3 items costs $6.75.

Getting User Input

While there are more advanced ways, a simple way to get input is with fmt.Scanln(). This function will wait for the user to type something and press Enter.

go
package main

import "fmt"

func main() {
    var name string
    
    fmt.Println("Please enter your name:")
    fmt.Scanln(&name) // The & is important! It tells Scanln *where* to store the input.
    
    fmt.Printf("Hello, %s! Welcome to the Go Cafe.\n", name)
}

This little program will pause and wait for you to type your name, making your programs interactive!


Further Reading & References

To continue your journey, here are some excellent resources:

Challenge

Task

Your task is to write a Go program that declares product details using variables and a constant, calculates a final price, and then prints a formatted summary. This exercise will test your knowledge of package-level constants, variable declaration with var and :=, basic arithmetic operations, and formatted printing with fmt.Printf.

Requirements:

  1. At the package level (outside the main function), declare a constant named StoreTax and assign it the floating-point value 0.075.
  2. Inside the main function, use the short declaration operator (:=) to declare and initialize the following variables:
    • productName: a string with the value "Go Programming Mug"
    • quantity: an int with the value 100
    • onSale: a bool with the value true
  3. On a new line, declare a variable named unitPrice of type float64 using the var keyword, and assign it the value 14.99.
  4. Declare another variable named totalPrice also using the var keyword. Calculate the price after tax (unitPrice + (unitPrice * StoreTax)) and assign the result to this variable.
  5. Using a single call to fmt.Printf(), print a formatted, multi-line string containing all the product information. The output format must strictly adhere to the structure specified in the expected output description, using appropriate format verbs.

Expected result

Your program's output must be a single, multi-line string generated from one fmt.Printf call. It must exactly match the format below, including all text, spacing, punctuation, and line breaks.

text
--- Inventory Details ---
Product: "Go Programming Mug"
Quantity: 100
On Sale: true
Unit Price (incl. tax): $16.11
Data type of 'quantity': int
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.