Hossam Mourad

GoLang Initialization Statement

May 03, 2020


This is my first post in this new blog about my technical thoughts and things I learn and would like to document and share it with other people.

excited gif

Today I learned about a feature in GoLang called Initialization Statement. Let me explain it with an example:

x := 10
y := 5

if result := x / y; result == 2 {
  ...
}

What is happening here is that you’re initializing a new variable and assigning a value to this new variable in the if statement itself without the need to declare this new variable outside the scope of the if statement. Beside the obvious benefit of not needing to declare this variable outside the if statement, you also have access to this variable inside the if block.

Also, it can be used in any logical statement not only if.

A side note, the : before the = sign is the GoLang way of deferring the variable type without explicitly typing it.

So x := 10 is equal to var x int = 10


👨‍💻 If you think there is a mistake in this post or you want to discuss, you can follow me on Twitter or send me an email. Have a nice day!

Written by Hossam Mourad.
A software developer specializing in front-end development with a passion for software development as a craftsmanship not only writing working code.
Resume / Email / LinkedIn / GitHub / Twitter