Follow by Email

Sunday, 13 January 2019

How Go lang struct works

This is 3rd post of my Go lang experiment, if you are want to read about earlier post then go to


Struct are cool types, it allows to create user defined type.

Struct basic
Struct can be declared like this

type person struct {
   firstName string
   lastName string

this declares struct with 2 fields.

Struct variables can be declared like this
var p1 person

var construct will initialized p1 to Zero value, so both the string fields are set to "".

DOT (.) construct is used to access field.

How to define struct variables.
Couple of ways by which variable can be created.

var p1 person                                      // Zero value
var p2 = person{}                                  //Zero value
p3 := person{firstName: "James", lastName: "Bond"} //Proper initialization
p4 := person{firstName: "James"}                   //Partial initialization

p5 := new(person) // Using new operator , this returns pointer
p5.firstName = "James"
p5.lastName = "Bond"

Struct comparison
Same type of struct can be compared using "==" operator.

p1 := person{firstName: "James", lastName: "Bond"}
p2 := person{firstName: "James", lastName: "Bond"}

if p1 == p2 {
fmt.Println("Same person found!!!!", p1)
} else {
fmt.Println("They are different", p1, p2)

this shows power of pure value, no equals/hashcode type of things are required to compare, language has first class support to compare by value.

Struct conversion
Go lang does not have casting, it is supports conversion and it is applicable to any types not just struct.

Casting keep source object reference and put target object struct/layout on top of it, so in casting any changes done to source object after casting is visible to target object.
This is good for reducing memory overhead but for safety this can cause big problem because values can change magically from source object.

On other end conversion copies source value, so after conversion both source and target have no link, changing one does not impact other one. This is good for type safety and easy to reason about code.

Lets look into some conversion example of struct.

type person struct {
   firstName string
   lastName string

type anotherperson struct {
firstName string
lastName  string

Both of the above are same in structure but these two can't be assigned to each other without conversion.

p1 := person{firstName: "James", lastName: "Bond"}
anotherp1 := anotherperson{firstName: "James", lastName: "Bond"}

p1  = anotherp1 //This is compile time error
p1 = person(anotherp1)//This is allowed

Compiler is very smart to figure out that these two types are compatible and conversion is allowed.
Now if go and make change in otherperson struct like drop the field/ new field/change the order then it becomes not compatible and compiler stops this!

When it does allow conversion then it allocate new memory for target variable and copies the value.

For eg
p1 = person(anotherp1)
anotherp1.lastName = "Lee" // Will have not effect on p1

How struct are allocated

Since it is composite type and understanding memory layout of struct is very useful in knowing what type of overhead it comes up.

Current processor will do some cool things for fast & safe read/write.
Memory allocation will be aligned to word size of underlying platform ( 32 bit or 64 bit) and it will be also aligned based on size of the type for eg 4 byte value will be aligned to 4 byte address.

Alignment is very important for speed and correctness.
Lets take example to understand this, in 64 bit platform word size is 64bit or 8 byte, so it will take 1 instruction to read 1 word.

Memory Layout
Value shown in red is 2 byte and if value shown in red is allocated in 2 words(i.e at the boundary of word) then it is going to take multiple operation to read/write value and for write some kind of synchronization might be required.

Since value is only 2 byte, so it can easily fit in single word so compiler will try to allocate this in single word

Single word allocation
Above allocation is optimized for read/write. Struct allocation works on same principle.

Now lets take example of struct and see how what will be memory layout

type layouttest struct {
b  byte
v  int32
f  float64
v2 int32

layout of "layoutouttest" will look something like below

[ 1 X X 1 1 1 1 X ][1 1 1 1 X X X X][1 1 1 1 1 1 1 1][1 1 1 1 X X X X]

X - is for padding.
It took 4 word to place this struct and to get the alignment by data type padding is added.
If we calculate size of struct ( 1 + 4 + 4 + 8 = 17) then it should fit value in 3 word( 8*3 = 24) but it took 4 words( 8 * 4 = 32). It might look like 8 bytes are wasted.

Go gives full control to developer about memory layout, much more compact struct can be created to get to 3 word allocation.

type compactlyouttest struct {
f  float64
v  int32
v2 int32
b  byte

Above struct has reordered field in descending order by size it takes and this helps in getting to below memory layout

[ 1 1 1 1 1 1 1 1 ][1 1 1 1 1 1 1 1][1 X X X X X X X]

In this arrangement less space is wasted in padding and you might be tempted to use compact representation.

You should should not do this for couple of reason
 - This breaks the readability because related fields are moved all over the place.

 - Memory might not be issue, so it could be just over optimization.

 - Processor are very smart, values are read in cacheline not in word, so CPU will read multiple words and you will never see any slowness in read. You can read about how cache line works in cpu-cache-access-pattern post.

 - Over optimization can result in false sharing issue, read concurrent-counter-with-no-false-sharing to see impact of false sharing in multi threaded code.

So profile application before doing any optimization.

Go has built in packages for getting memory alignment details & other static information of types.

Below code gives lot of details about memory layout

unsafe & reflect package gives lot of internal details and looks like idea has come from java

Code used in this blog is available @ 001-struct github

Thursday, 10 January 2019

what are Golang Types

Go is strongly typed language and type is life. Language has rich types and good support for extension of type. Type provides integrity.

In this post i will share some of primitive types and how Go handles them.

Everything is 0 or 1 in computer and only these 2 values are used to represent any values we want.
Arrangement of 0 or 1 tells what is the value.

Take a example of byte value at some memory location


What is it ? You need type information .

If type is int then value is 10, if type of enum then some other value.

Type information tell us about value and size for eg if type is Boolean then it tells it is single byte value.

Information about types supported by Go can be found at Lang Spec Types  page.

How to declare variable ?

var variablename type
variablename := value // Short declaration

Both of above declare variable but the way it is initialized is very different.

Var creates and initialized with ZERO value of its type,  Zero value is very special it makes code bug free and clean! No null checks.

Zero value is based on Type so for integer type it is zero, boolean it is false , string it is empty.

Go has some type like int that gets size based on underlying architecture, for eg it will be 4 bytes(i.e 32 bit arch) or 8 bytes( 64 bit arc). This is also good example of mechanical sympathy to underlying platform.

Examples of variable declaration

Alias for built in type

This is very powerful feature and it allow built in types to be extended by adding behavior .
Example of type alias

In above example RichInt has toBinary function that returns binary value.  I will share later how to extend types when we explore methods of types.

Casting Vs Conversion
Casting is magic, it allows to convert one type to another implicitly. How many times in java you lost value when long/int casting or double/float.
Go has concept of conversion, you explicitly convert from x to y type and pay the cost of extra memory at the cost of safety.

Go lang spec has some good examples.

Some real custom types
Go lang has support for Struct type, it is pure value type , no noise of behavior attached to it.
It gives control of memory layout, you can choose really compact memory layout to avoid padding or to add padding if required.

Struct can be declared like below

type person struct {
firstName string
lastName  string
        age int

Once struct is defined then we can create value of struct type.
It is value not object just remember that!

value can be created using below code

var p1 person

above code create value and initialized it with zero value, string is initialized to empty value and int to 0.
No null check is required when processing p1 because it is initialized to ZERO value

Short declaration can be used to specified non zero or other value

p2 := person{firstName: "James", lastName: "Bond", age: 35}

Zero value and convenient way to creating value kills the need of having constructor or destructor in Go.
You can now start seeing power of value. No overhead of constructor/destructor/ or complex life cycle.

I know you will have question on what about special init code or clean up code that is required ?

behavior are handled very differently, we will go over that in later post.

Struct can be nested also and Zero value or short declaration works like magic!

We will create additional struct

type address struct {
address1 string
address2 string
city     string

type contact struct {
landLine int
mobile   int

type person struct {
firstName      string
lastName       string
age            int
add            address
contactDetails contact

p3 := person{firstName: "James", lastName: "Bond", age: 35,
add:            address{address1: "30 Wellington Square", address2: "Street 81"},
contactDetails: contact{mobile: 11119999}}

Code used in blog is available @ letsgo github repo

Is it worth learning Golang ?

I was looking for new language to learn and Go looked very good candidate. It is getting popular due to its simplicity and power.

 It is created by some of best minds of our industry
  • Robert Griesemer  - Google V8 javascript engine, Java hotspot virtual machine
  • Rob Pike -UNIX and co creator of world most popular character encoding UTF8
  • Ken Thompson - UNIX, B ,C  language and creator of  UTF8
Now we have so many language choices. 
For ease of programming people use dynamic language like Python, Ruby , Javascript etc and for safety options are C++, Java, C#, Functional or VM based lang( Scala,Clojure etc)

So it becomes like if you want ease then give up on safety or vice versa. Some of new lang came with fancy syntax to give both but made it really hard learn.

Go took very different approach(i.e still using curly braces) by keeping the syntax simple that most of the programmer can read the code and solve the hard issues like 

 - Memory management/Garbage collection.
 - Making pure value types. No abstraction on top of abstraction. Data oriented design.
 - Design for Multi core.
 - Distributed computing support.
 - Access to low level programming construct.
 - Portable to many OS.
 - Interesting module system and dependency management.
 - Very simple error handling.
 - Interesting support for OOPS.
 - Easy to read and simple mental model.  No hiding of cost like how much memory allocation or CPU processing required.

Pictures are better than thousands words, so i picked up some content from GoCon Tokyo


If you want learn new programming language today then Go looks very interesting choice.
It is not perfect , read about things that community don't like @ go-is-not-good also to get idea about what is left out in Go.

I am starting to learn Go and will be sharing my experience about it.
Lets Go for it:-)