2 min read

Value Semantics In Go

Value Semantics In Go

Lets see how a program execution takes place in Go Lang, lets try to understand Mechanics and Semantics of the program execution and memory allocation. Mechanics meaning how things work where as Semantics on how things behave.

Whenever a Go program is ready to be executed , it gets a logical processor say P for every core that is identified on the host machine. The P is given a Real time operating system thread say M, which get scheduled on the core from the OS scheduler. Path of execution in a program takes place at the Operating system level as well as the Go level. At the Operating system level it is done by M and the Go level it is done by Go routine.

Every line of code is basically reading or writing memory. Threads are paths of execution at the operating system level. There are data structures consisting of stacks, heaps and data segments . Value semantics is what you see is what you get . Lets see an example of how pass by value works.

Pass By Value

Here above the execution takes place in two levels of isolation, in a stack each frame have its own set of values. A stack has frames where go routines run. The first execution is initialization of a variable. It takes place in the 1 st frame of the stack and gets a memory address allocated to it. So the Go routine is currently active on the 1st frame, as the main make another call to the inc func now the Go routine is active on the 2nd frame where the increment takes place. So we get the value 2 and the address the value is stored in. As we now again move to the 1st frame , the Go routine get active on the 1st frame, and the 2 nd frame is now erased and is invalid and the value of i it printed with address value and type.

Value semantics has no efficiency but we copy the data in frames and each frame is isolated and mutable, thus reducing the side effect. Pass by value is that we are making copies of data as we cross over program boundaries.