DEV Community

Cover image for Introduction to Go: Variables, Pointers, Memory Allocation, and Assignments
Walid LAGGOUNE
Walid LAGGOUNE

Posted on

1

Introduction to Go: Variables, Pointers, Memory Allocation, and Assignments

I’m Walid, a backend developer who’s currently learning Go and sharing my journey by writing about it along the way.

Introduction to Go: Variables, Pointers, Memory Allocation, and Assignments

Go (Golang) is a statically typed, compiled programming language designed for efficiency, scalability, and simplicity. Understanding variables, pointers, memory allocation, and assignment operations is crucial for writing effective Go programs. In this article, we will cover these fundamental concepts in depth.

Variables in Go

A variable in Go is a named storage location that holds a value of a specific type. Go enforces static typing, meaning each variable has a fixed type determined at compile time.

Declaring Variables

Go provides multiple ways to declare variables:

Using the var Keyword

var x int // Declaration without initialization, defaults to zero value (0)
var name string = "GoLang" // Explicit type declaration with initialization
Enter fullscreen mode Exit fullscreen mode

Short Variable Declaration (:=)

count := 42 // Implicit type inference; `count` is inferred as `int`
message := "Hello, Go!" // `message` is inferred as `string`
Enter fullscreen mode Exit fullscreen mode

Note: The := operator is only available within functions and cannot be used at the package level.

Multiple Variable Declarations

var a, b int = 10, 20
x, y := 1.5, "tuple assignment"
Enter fullscreen mode Exit fullscreen mode

Pointers in Go

A pointer is a variable that stores the memory address of another variable. Pointers allow direct memory manipulation and can be used for efficient function argument passing.

Declaring Pointers

var ptr *int // Declares a pointer to an int, initially nil
Enter fullscreen mode Exit fullscreen mode

Assigning a Pointer

x := 10
ptr := &x // `ptr` now holds the address of `x`
fmt.Println(ptr)  // Outputs memory address
fmt.Println(*ptr) // Dereferencing the pointer (outputs 10)
Enter fullscreen mode Exit fullscreen mode

Modifying Value Through Pointers

*ptr = 20 // Changes `x` value to 20
fmt.Println(x) // Outputs 20
Enter fullscreen mode Exit fullscreen mode

Comparing Pointers in Go and C

Go's pointers are similar to C's but with important differences:

  • No Pointer Arithmetic: Unlike C, Go does not allow pointer arithmetic (e.g., ptr++ is invalid).
  • Garbage Collection: Go has an automatic garbage collector, whereas C requires manual memory management (malloc and free).
  • Safer Memory Management: In Go, dangling pointers are less common because memory is managed automatically, whereas in C, improper memory management can cause memory leaks and segmentation faults.
  • Nil vs. NULL: In Go, uninitialized pointers default to nil, whereas in C, the equivalent is NULL.

Example in C:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *p = (int*)malloc(sizeof(int));
    *p = 10;
    printf("%d", *p);
    free(p); // Must manually free memory
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Equivalent in Go:

package main
import "fmt"

func main() {
    p := new(int)
    *p = 10
    fmt.Println(*p) // Memory is managed by Go's garbage collector
}
Enter fullscreen mode Exit fullscreen mode

Memory Allocation: new() and make()

Go provides two functions for memory allocation: new() and make(), each serving different purposes.

Using new()

new() allocates memory for a type but does not initialize it beyond zero values.

p := new(int) // Allocates memory for an int and returns a pointer
fmt.Println(*p) // Prints zero value (0)
Enter fullscreen mode Exit fullscreen mode

Using make()

make() is used for slices, maps, and channels, initializing them properly.

s := make([]int, 5) // Allocates and initializes a slice of length 5
fmt.Println(s) // Outputs [0 0 0 0 0]
Enter fullscreen mode Exit fullscreen mode

Lifetime of Variables

In Go, variable lifetime is determined by its scope:

  • Global Variables: Live throughout the program execution.
  • Local Variables: Exist only within the function where they are declared.
  • Heap-Allocated Variables: Managed by Go's garbage collector.

Assignments and Tuple Assignments

Assignment in Go follows a straightforward syntax but has some interesting features.

Simple Assignment

x := 10
x = 20 // Reassigning x to 20
Enter fullscreen mode Exit fullscreen mode

Tuple Assignment

Tuple assignment allows swapping values without a temporary variable.

a, b := 5, 10
a, b = b, a // Swaps values of a and b
fmt.Println(a, b) // Outputs 10, 5
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding variables, pointers, memory allocation, and assignments is fundamental in Go. These concepts provide a solid foundation for working with Go’s memory model, performance optimization, and writing efficient code. Compared to C, Go's pointer system is safer and more manageable due to its garbage collection and restricted pointer operations. Mastering these concepts will help you develop robust and scalable Go applications.

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed: Zero in on just the tests that failed in your previous run
  • 2:34 --only-changed: Test only the spec files you've modified in git
  • 4:27 --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • 5:15 --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • 5:51 --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay