Saturday 5 October 2024

Go's pointers in nutshell

Why?

It's simply more efficient. They avoid copying large amounts of data when passing variables to functions.

What are they?

A pointer is a variable that contains the memory address of another variable, instead of containing a value directly. 

  • Value: The actual content (for example : the string "walk"). 
  • Address: The memory location where the value is stored (for example : 0xc00001a0a8, a value that represents the point where RAM saves the "walk" value).

To make it easier to understand, think of it like a car: the key you use to drive is your pointer, and the car is the value. The key is not the car itself, but it allows you to access it. Similarly, a pointer is not the data, but it allows you to access the data in memory.

Syntax 

You need to remember 2 symbols: '&' and '*'.

Types of Pointers:

  • Pointers to Primitive Types: Such as *int, *float64, *string, etc.
  • Pointers to Structures: Such as *Parking.
  • Pointers to Functions: Even functions can have addresse

Declaration of a pointer to a variable of type 'string'

var myKeys *string

Assignment of a variable of type 'int'

var car = "gt-r"
myKeys = &car
fmt.Println(myKeys) // 0xc000114040fmt.Println(*myKeys) // "gt-r" 

 

Structures and Small Modifications

func updateCarPower(myKeys *Car, newCv int) {
	myKeys.cv = newCv
}

func main() {
	car := Car{
		Name: "gt-r",
		cv:   480,
	}

	updateCarPower(&car, 520)

	fmt.Println("Name:", car.Name, "CV:", car.cv) // Name: gt-r CV: 520
}

When not to use pointers

Let's look at a case where using pointers is not necessary. If you don't need to modify the Car object but only read or process data without altering the original state, there's no need to pass a pointer.

 func getCarInfo(c Car) string {
return fmt.Sprintf("Name: %s, CV: %d", c.Name, c.cv)
}

func main() {
car := Car{
Name: "gt-r",
cv: 480,
}


info := getCarInfo(car)

fmt.Println(info) // Name: gt-r, CV: 480
}

in general, pointers are often used when the data size is large, but if you're only changing a primitive type, it's not worth using them.

This is just a small article on pointers in Go. I didn't cover other commonly used data structures, like slices, to avoid making it too heavy. If there's interest, I’ll add a section on slices. I hope you enjoyed it!

I hope you enjoyed it!