What is a Pointer
Lesson 2 of 19 in Coddy's Functions and Pointers in Golang course.
The first question that we need to answer is, what is a pointer? We've already learned about variables, which we defined as boxes that store our values. Pointers, on the other hand, are boxes that store addresses instead of values.
When we create a variable in any programming language, this variable is stored in memory, and every space in memory has an address. For example, if we define a variable like this:
var name = "Coddy"We can represent this in memory like this:
To be able to get any value from memory, we need an address. So, the address tells us where this space is in memory.
On the other hand, a pointer is a box where we store the memory address instead of the value. That's why we call it a pointer because it points to a memory address.
The syntax to define a pointer is like this:
var name = "Coddy"
namePointer := &nameHere, we define a pointer with the name namePointer and point & to the address of the name variable.
We can define a new pointer with the default value, which is nil, like this:
var coddy *stringThis syntax * creates a new pointer called coddy with type string, and the default value of a pointer is nil.
To print the address stored in the pointer, we just pass the name of the pointer like this:
fmt.Println(coddy)To print the value that is stored in the pointer address, we do it using an asterisk *:
fmt.Println(*coddy)Challenge
Easy- Declare a variable called a with a value of 200.
- Declare a new pointer called aPointer of type int.
- Point the address of the variable a to the pointer aPointer.
- Print the value of the pointer aPointer and variable a.
Try it yourself
package main
import "fmt"
func main() {
// Declare a variable called a with a value of 200.
// Declare a new pointer called aPointer of type int.
// Point the address of the variable a to the pointer aPointer.
// Print the value of the pointer aPointer and variable a.
fmt.Println("the value of the pointer:",?)
fmt.Println("the value of the variable :",?)
}All lessons in Functions and Pointers in Golang
1Introduction
Introduction4Rebuild Go Strings Functions
Strings in GolangJoin FunctionContains FunctionIndex FunctionRecap Challenge #1