Translate

Friday, 29 August 2014

Pointers in Go Lang

Pointers is a kind of concept to be learned with eminence and passion. I don’t think, a short and terse explanation on Pointers is really worth full. Unlike C Lang Pointers(open to perform and better performer one way), Go’s pointers are designed with extreme care so that certain Pointer manipulations are separated from core design and kept in a package called “unsafe”. In this post, concept has been segregated into different sections starting from creating pointer to different scenarios in Go Lang.

Here are the sections the whole concept is segregated into

What is a Pointer?


What are the differences between Go Lang and C pointers?

Why Java does not have pointers?

What are main advantages of pointers in Go Lang?

Maintaining object life cycle using pointers

Unsafe package in Go Lang

Pointers in function parameters

Pointers in Structs and Struct receivers, Struct methods

Pointers in Interfaces


Here is the explanation


What is a Pointer?
Like in C language, Pointer is a variable which is used to store address of another variable. Every variable is stored in a memory location and every memory location has an address hence, Pointer in Go Lang is used to hold an address of another variable. Have a look at the below figure.


50 is the value of a variable and 1001 is the address of 50. So pointer holds 1001 which is the address of 50 and even pointer also has its own address which is 2047. So far, Go’s pointers story is same like C Language.



Go uses &(ampersand) and *(asterisk) operators for pointer manipulations. In addition to them there are other types and packages available for pointer manipulations. We will discuss about them in later sections described below.


Just keep in your mind that a pointer variable always keeps the address of a variable.

The below figure explains a simple and very first pointer example.


Creating Pointers example

Download above example from :Pointers example-1
De-Reference a Pointer: Any pointer variable can be de-referenced by using “nil”. E.g.
var value int8 = 100
var Ptr *int8 = &value
Ptr=nil
Now Pointer variable “Ptr” is not referenced to any variable.
void Pointer : Like in C language there is no discrete keyword like void in Go Lang. Void pointer similar functionality can be obtain using unsafe package.
Pointer arithmetic: This feature is not included as a core feature in Go Lang. According to Google’s view pointer arithmetic to be done with great care and necessity.  
(Other sections yet to be completed so stay tuned)
 

No comments:

Post a Comment