golang tutorial - Pointers In Golang | Golang Pointers - golang - go programming language - google go - go language - go program - google language
Pointers In Golang
- Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers.
- Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
Output for the above code
What Are Pointers?
- A pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its memory address.
- A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer.
- Typical real-time example, a page number in a book's index could be considered a pointer to the corresponding page;
- Dereferencing such a pointer would be done by flipping to the page with the given page number and reading the text found on the indexed page.
pointer variable declaration syntax:
- type is the pointer's base type; it must be a valid C data type
- var-name is the name of the pointer variable.
- The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication.
A sample example program in "C" language for pointers
How to use Pointers?
- Define a pointer variable
- assign the address of a variable to a pointer and
- finally access the value at the address available in the pointer variable.
- This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
golang , gopro , google go , golang tutorial , google language , go language , go programming language
Output of the above golang program
nil Pointers in Go
- Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned.
- This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer.
- The nil pointer is a constant with a value of zero defined in several standard libraries.
golang , gopro , google go , golang tutorial , google language , go language , go programming language
output for the above golang program
- None of the programs were not permitted to access memory at address 0 because that memory is reserved by the operating system.
- The memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location.
- if a pointer contains the nil (zero) value, it is assumed to point to nothing.