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)
 

Friday, 22 August 2014

Types in Go Lang

Understanding the way “Types in Go Lang” work is a very essential step in order to write better and precise programming.

Go is a statistically typed language. That means, each variable has a type and once type is given to a variable that type cannot be changed. But of course there are situations where we need to switch between types using dynamic typing.

· There are two Types in Go Lang

1.Named types : A type that is declared with pre declared type.Pre declared types: Boolean, Numeric and String types

2.Unnamed types: A type that is declared using previously declared types or a composition. Composite types:array, struct, pointer, function, interface, slice, map, and channel types. Composite types are constructed using literals

·Static or Dynamic type

1.Static type: A type of a variable when it is declared. Generally all types are static types. So once a variable is declared with a type it does not change

2. Dynamic type: Dynamic type is only applicable for interface variables. A type varies during the execution of the program. Ultimately any dynamic type should be assigned to a static type. I have explained more about dynamic type in type assertion section below.

 Rules to follow in types


· Implicit conversion is not possible from one type to another type in Go Lang, even though the value belongs to a pre defined type. So unlike in other programming languages int16 cannot be implicitly converted to int32.

var age uint8 = 47
var newage int16 = int16(age)// This is called explicit //conversion. Since age is uint8 explicitly converted



·  Unlike Java and C#, Go does not differentiate stack and heap memory.

· Methods can be assigned only to the types declared in the same package. Take a look at the example below. 


func (s string) Length(str string) int {
    return len(str)
}
func main() {
    var name string = "About types  in Go Lang"
    fmt.Printf(name.Length(name))
}

The above program compiles an error, because string type is not declared in the same package. String is a pre declared type; hence, the rule is receiver of the method should be defined in the same package.

·  The below figure explains, how to create type from the underlining primitive types and how to create type from an existing type. It also explains type casting between types



                          Creating types from underlying types
Download above program from Creating and casting types
Type assertions
As all of us know and have experienced the importance of dynamic types in Java and C# programming. Dynamic types are very useful when using generic frameworks and design patterns. Dynamic type in Go Lang can be created by using empty interface {}.See the below code snippet


//The below types are declared dynamically using empty interface
 var name interface{} ="Jiten"
 var age interface{} = 33
  var address interface{} ="Bur Dubai, Dubai"

Once a value is assigned to a dynamic type, at any point of time it has to be assigned to its original type. Similar concept is boxing and unboxing in .NET family languages. Go’s way of dynamic type to static type is called type assertion. The below figure explains how to cast from dynamic type to variable’s actual type.

Type assertion & casting
  Download above program from Type assertion and casting
 
So far in this post, I gave overall information about types. Going forward I will post more specific about Pointer, Array, Slice, Map, Func, Struct , Interface and Channel types. Each post would give precise information about each of the types.

Enjoy Go Lang, stay tuned, thanks for reading.

Wednesday, 20 August 2014

Overview of Go Lang


Go Lang project initiation

·       Go Lang is an open source project started at Google in 2007. Main designers of this language are Robert Griesemer, Rob Pike(Unix designer), and Ken Thompson(Unix designer). In 2009 it was declared as an open source project and then about 450 developers from various parts of the world involved in writing various packages for Go Language.

·       Go Lang core libraries are designed using C Language and later using Go lang itself.

·       Go Lang features were influenced by C, Python, Pascal and Java languages.

Why Go Lang?

·       Go is a general purpose programming language like C language. Preferably a systems programming language.

·       C language was developed about half a century ago, and programming community still consider it is worth to learn because of its robustness, simplicity and performance. But certainly it lacks in some areas like utilizing multi core processors, cloud computing and Web, since at the time of C Lang development, these features did not exist.

·       The aim of Go language is not to replace C language. In fact it uses C language for Go’s core packages. So the aim is to  produce a concrete general purpose language similar to C in terms of simplicity , performance and robustness by utilizing latest updates in hardware and software technology to ease programming.

·       All programming languages right now are targeted to develop enterprise application (like Java,C#) , web applications(PHP ,RUBY etc..) or for any specific purpose . But there is no single modern language which can fulfill the gap that a general purpose language can suffice by giving advantages of Java like garbage collection, Python and VB like simplicity and C++ like performance. Here Go exactly fits.

Go- important features

·       Works on all major operating systems (Windows, Mac, Linux, Plan9 etc...).

·       Wonderful tool set for cross compilation on various processors and OS architectures like ARM 5, ARM 6, Win 32, Win 64, Linux 32,64 etc…

·       Comparatively fast compilation, hence application opens faster than many other programming language applications.

·       Hundreds of packages already are developed , tested and used by open source community.

·       Community developed many IDEs to develop Go applications. Some of them are Eclipse Add in, IntelliJ for Go, LiteIDE (Specially designed for Go).

·       Like many other programming languages Go Lang does not entertain warnings during compilation. Compiler gives only errors , no warnings. For e.g. if you declare a variable or a package and it is not used then according to Go Lang compiler it is an error.

Go Lang- important features

·       First class focus on concurrency patterns using Go routines and channels. Hence, better performance can be obtained from multi core systems. This is one of the key reasons of its wide adaptability.

·       Go is a very light weight language. There are fewer checks by compiler in comparison to  Java, C# and C++ etc... so compilation with Go is faster than many other language compilations.

·       Go is a Garbage collected language. Statically typed and type safe language.

·       There is no need to give “;” at the end of each statement. Compiler can automatically understand from the source code. Similarly programming has been simplified whereever it is possible in Go Lang.

·       Easy and effective variable type declarations.

·       Multiple return values from functions and methods.

·       Has different way of exception handling. There are no try catch blocks in Go.

·       Arrays, Slices and Maps are innovative and robust.

·       Innovative and different approach for Object Orientation. No classes in Go Lang but we can obtain similar features from structs and interfaces

·       Different and innovative approach in using Interfaces.

·       Many packages are available for Web, Servers, JSON Web Services and database programming. Please check the following link for all approved packages https://golang.org/pkg/

 
Information on downloads

·       Download latest Go version from http://golang.org/dl/

·       Download LiteIDE from http://sourceforge.net/projects/liteide/files/
 

Since Go is a new language with different approach, there is always a chance to think and program in an innovative out of the box way . Enjoy learning Go Lang.

Stay tuned for more tutorials on Go language features.

 

 

 

 

 

 

 

 

Variable declaration and assigning values in Go Lang

   There are various ways to declare and assign values to variables in GoLang.
  • Declaring variables using var keyword
  • Declaring  variables and assigning values with a special assignment operator :=
Below images depict various ways of declaring and assigning values to variables


Variable declaration using var keyword and assigning values



Download above code from Variable declaration example-1

As mentioned earlier there is another way of declaring variables at the time of assigning values to them. It can be called as ad-hoc declaration . The below image explains how to do that
Variable declaration and assign value in an ad-hoc way
 Download above code from Variable declaration example-2

Thanks for reading, please do write your comments and correct me if some thing is wrong or some thing to be added to it. I will write advanced techniques in Go Lang in my upcoming posts..