Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Pointers and Memory Model Basics | Pointers, Memory, and Advanced Features
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Advanced Go

bookPointers and Memory Model Basics

Glissez pour afficher le menu

How Pointers Work in Go

A pointer in Go is a variable that stores the memory address of another variable. Pointers allow you to reference and manipulate data in memory directly.

Memory Addresses

  • Every variable in Go is stored at a specific memory address;
  • You can use the & operator to get the address of a variable;
  • Memory addresses are typically shown as hexadecimal numbers.

Pointer Types

  • A pointer type is defined using the * symbol followed by the type of the value it points to (for example, *int);
  • A pointer of type *int can only point to an int value.

Dereferencing

  • Dereferencing means accessing the value stored at the memory address a pointer refers to;
  • Use the * operator to dereference a pointer and read or modify the underlying value.

Example: Pointer Declaration, Assignment, and Dereferencing

package main

import "fmt"

func main() {
    var x int = 42           // Declare an int variable
    var p *int = &x          // Declare a pointer to int and assign x's address
    fmt.Println("x:", x)     // Print value of x
    fmt.Println("p:", p)     // Print address stored in p
    fmt.Println("*p:", *p)   // Dereference p to print value at address

    *p = 100                 // Change value at address via pointer
    fmt.Println("x (after *p = 100):", x) // x is updated
}

This code demonstrates:

  • Declaring a pointer to an int;
  • Assigning it the address of a variable using &;
  • Accessing the value with * (dereferencing);
  • Modifying the value through the pointer.

Safe Usage of Pointers in Go

Using pointers safely in Go is essential for building reliable programs. You must understand how to handle nil pointers, initialize pointers properly, and avoid unsafe operations.

Nil Pointers

  • A pointer with no assigned memory address is a nil pointer;
  • Dereferencing a nil pointer causes a runtime panic;
  • Always check if a pointer is nil before using it.

Pointer Initialization

  • Use the new function or assign the address of an existing variable to initialize a pointer;
  • Uninitialized pointers default to nil.

Avoiding Unsafe Operations

  • Never dereference a pointer without ensuring it is not nil;
  • Do not use pointers to variables that may go out of scope;
  • Avoid pointer arithmetic, as it is not supported in Go and leads to unsafe code.

Example: Safe Pointer Usage and Nil Checks

package main

import "fmt"

func printValue(ptr *int) {
    if ptr == nil {
        fmt.Println("Pointer is nil; nothing to print.")
        return
    }
    fmt.Println("Value:", *ptr)
}

func main() {
    var a int = 42
    var p1 *int = &a         // Properly initialized pointer
    var p2 *int              // Uninitialized, defaults to nil

    printValue(p1)           // Prints: Value: 42
    printValue(p2)           // Prints: Pointer is nil; nothing to print.
}

This example demonstrates how to safely use pointers by checking for nil before dereferencing. Always initialize pointers and validate them before use to prevent runtime errors.

question mark

Which statement best describes a pointer in Go?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 1

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 3. Chapitre 1
some-alt