Today is the 6th day of #30DaysOfCode challenge. I started my day by reading the Go Programming Langauge Book by Alan A. A. Donovan and Brian W. Kernighan. And I would like to share what I have learned today with you so let's just jump right into the code.
First, Take a look at the image below and try to understand the code.
There are multiple ways to declare a variable and I learnt a new way today. You can also declare a variable using new() function. The new function takes the type(such as int bool string) as an argument and it returns the address of the memory location. In the example, the new function is creating an integer type variable and it is returning the address. In the line just below, we are accessing the value of the variable using the * symbol.
There is just one thing that I want to learn from this post at least, which is that the * symbol is used to access the value and & is used to access the address of the variable in the memory. And if you understand this then it will help you in understanding how pointers work. But just keep in mind that when * is used before a type (such as int, bool or string), it means a different thing. We will talk about this in my later posts. So don't worry about that for now. Just know that in this example, it means that the function takes a pointer of type int.
In the example, we have a function which increments the value of the variable. The function takes a pointer of type int as an argument. We are using the * symbol to access the value and we are returning the value. In the main function, we are using & symbol to access the address and we are passing the address in the incr() function. The function runs and it increments the value of the variable by 1. And that's all that our program does.
I hope that it's all clear to you. If you have any question then feel free to ask in the comments below.
Alright! That's all for today and I will see you in my next post. Bye.