Table of contents
- Introduction
- Multiple ways variables can be declared in Golang
- Declaring variable with a value (WAY 1)
- Declaring variable "without" a value (WAY 1.1)
- Declaring variable without mentioning its data type (WAY 2)
- Most shortcut way to define a variable (WAY 3)
- One variable? How to declare bunch of them?
- Wait a second isn't go statically typed?
- The End
Introduction
Well i know you guys are not a baby, i know that you guys can make variables in a programming language, but do you really think i would put hours of time writing a blog just for variables? nah! here are things i bet "most of you" did not know about variables in Golang.
Lets GO! and learn variables once and for all in Golang.
Multiple ways variables can be declared in Golang
var
keyword withdata type
mentioned with it, can be used.
This way is used very less, like come on it takes time to write all of this.var
keyword with "no"data type
mentioned with it, can be used.
This way is used quite frequently as we dont need to declare the type of the variable, but still not very heavily.:=
shortcut can be used.
This way is very heavily used, as it saves typing. We don't need to declare a variable'sdata type
nor we have to writevar
keyword.
Declaring variable with a value (WAY 1)
If you know what a variable's value beforehand, you can declare variables and assign them values on the same line. Like this is the most common way to declare a variable "by giving it a value we want like int, string, bool etc."
Example
package main
import "fmt"
func main() {
var i int = 190 // telling go "this variable contains a int"
var s string = "Bro I am String" // telling go "this variable contains a string"
fmt.Println(i)
fmt.Println(s)
}
Inside the main function:var i int = 190
: This declares a variable named i
of type int
and initializes it with the value 10.var s string = "Bro I am String"
: This declares a variable named s
of type string
and initializes it with the value "Bro I am String".
The Go language has strong static typing, which means you need to specify the type of a variable when you declare it. (But we have other way to not specify the datatype of variable when declaring it, like the way 2 and way 3 we discussed.)
Declaring variable "without" a value (WAY 1.1)
The keyword var
is used for declaring variables. After writing var
we write the name
of the variable we want to give it, then we write the datatype
of that variable.
In way 1 we gave it value also but listen "we dont need to".
If you want to declare a variable with no value (actually its "zero value", explained later) the we can also do that.
Example
package main
import "fmt"
func main() {
var i int // made variables with no value initialization "zero value"
var s string
i = 190
s = "Bro i am string"
fmt.Println(i)
fmt.Println(s)
}
Two variables are declared here right now:
- i of type int
- s of type string
At this point, they're declared and it look like they are completely empty as we have given them no value, actually that look like that but that's not true.
The variables declared earlier are now assigned values later by us:
- i
variable is later assigned a value 190
- s
variable is "later" assigned a value "Bro i am string"
Now explaining that "zero value" thing:
Look a variable when defined like this var s string
might make you think that it has no value what so ever, what that's wrong, if when we don't give the variable a value and declare it like this, golang gives it a "zero value". Zero "0"? NAH! Look at this below table:
Data Type | Zero Value |
int64 or int32 or int16 or int8 or int | 0 |
float64 or float32 | 0.0 |
string | "" (empty string) |
bool | false |
pointer | nil (represents no memory address) |
If you defined var s string
the zero value of string is "" (empty string). So the value right here at this point of this code var s string
is "" (empty string), which is given by golang.var i int
here at this point in this code the value of i
is 0 (int 0) which is the "zero value" of int
datatype in golang.
Just like that we every datatype in golang has its own different "zero value" which is predefined by golang.
So never make the mistake of thinking that a variable defined with no value has "no value" or its "empty" or "undefined" or "null". It contains its "zero value". So always refer this table.
Declaring variable without mentioning its data type (WAY 2)
You can omit the variable type while the declaration the variable. Meaning when declaring a variable using var
you don't need to write int
, string
, bool
etc.
If you want to make a int
datatype variable
then just say:var value = 3
Instead ofvar value int = 3
This saves us a lot of typing.
By the way the most important thing to tell you guys , its is called "type inference". This is a feature or something that golang has, which lets us define variables without needing to write their datatype during initialization.
What type inference do?
It looks at the value you gave like 3, "string", true, false then it determines like okay if 3 is put as the value in this variable it is a int
if "sora tora" is put as the value then its a string
and like that.
So dont forget "type inference" this is what lets you do this.
Example
package main
import "fmt"
func main() {
var i = 190 // no need to define its data type, thanks to "type inference"
var s = "Bro i am string"
fmt.Println(i)
fmt.Println(s)
}
Here, two variables are declared and immediately initialized:
- i
is initialized with the integer value 190
.
- s
is initialized with the string value "Bro i am string"
.
Most shortcut way to define a variable (WAY 3)
The :=
operator, is used for defining variables in the most shortcut way. There is no need to use the var
keyword or declare the variable's datatype
.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
variable := "Bro i am string" // use := that's it my boy
fmt.Println(reflect.TypeOf(name))
}
Here, a string
is used as the value of variable named variable
. As :=
shortcut operator is we dont need to write var
and datatype
anymore. Golang behind the scenes uses type inference
to know the datatype
of the variable being declared using :=
.
One variable? How to declare bunch of them?
- Declaring bunch of same datatype variables
package main
import (
"fmt"
)
func main() {
// using var keyword and datatype declaration for this task
var fname, mname, lname string = "Brock", "Beast Incarnate","Lesnar"
// fname = "Brock", mname = "Beast Incarnate", lname = "Lesnar"
// using := for this as shortcut
m, n, o := 1, 2, 3 // all of same type
// m = 1, n = 2, o = 3
item, price := "Laptop", 2000 // we can define different types also in the same line
// here item = "Mobile" & price = 2000 (multiple variables in single line but of different types)
fmt.Println(fname + lname)
fmt.Println(m + n + o)
fmt.Println(item, "-", price)
}
- Declaring a bunch of variables of different datatypes
package main
import "fmt"
var (
product = "Laptop"
quantity = 93
price = 50.50
inStock = true
)
func main() {
fmt.Println(quantity)
fmt.Println(price)
fmt.Println(product)
fmt.Println(inStock)
}
I don't think by this point anyone of you couldnt understand this code, i hope you did. Its easy bro come on!
Declaring bunch of different variables of different types by using var
& ()
that's it.
Scope of Variables in Go: Where They Live and Breathe
Scope refers to the accessibility of a variable within your program. In simpler terms, it defines where a variable can be used and modified.
Two Main Scopes in Go:
Go primarily recognizes two main scopes for variables:
- Local Scope: Variables declared within a function, loop (for, if, etc.), or block of code (delimited by curly braces
{}
) have local scope. They are only accessible from within the block where they are declared. Once the control flow exits the block, the local variable can't exist and is removed.
Example:
Go
func greet(name string) {
message := "Hello, " + name + "!" // message variable has local scope
// meaning message variable cannot be accessed outide this greet function
fmt.Println(message)
}
func main() {
greet("Alice") // message is accessible here
// fmt.Println(message) // This would cause an error as message is out of scope
}
In this example, message
is declared within the greet
function, hence it has local scope. It can only be accessed and used inside that greet()
function.
- Global Scope: Variables declared outside any function or block have global scope. They are accessible from anywhere in your program (within the same package). However, it's generally recommended to minimize the use of global variables as they can lead to naming conflicts and make your code harder to reason about.
Example (Use with Caution):
Go
var globalMessage = "Welcome to Go!" // This has global scope
// can be accessed any where
func greet() {
fmt.Println(globalMessage)
}
func main() {
fmt.Println(globalMessage)
greet()
}
Here, globalMessage
is declared outside any function, giving it global scope. It's accessible from both main
and the greet
function.
Key Points on Scope:
Local variables take precedence over global variables with the same name. If a local variable is declared within a function that has the same name as a global variable, the local variable will be used within that function.
Use local scope whenever possible to isolate variables and prevent unintended side effects.
Global variables should be used with caution, especially in larger projects.
Wait a second isn't go statically typed?
Yeah i had this same question, like hey how the hell a programming language which is statically typed language like (c, c++, etc.) offers us the ways to declare variables without specifying its datatype with it?
It does make golang "feel" like python and javascript or we can say a dynamically typed language.
Still what makes it possible?
Type Inference in Go: Behind the Scenes of Not Needing to define DataTypes
Go is undeniably a statically typed language, meaning the data type of a variable must be explicitly declared or inferred at compile time. However, Go offers a convenient feature called "type inference" that simplifies variable declarations in certain scenarios.
How Type Inference Works
Type inference in Go stems from the go's compiler's ability to deduce the data type of a variable based on its initialization value or the context in which it's used. Here's a breakdown of the mechanics:
- Initialization with a Constant: When you assign a constant value (like a integer, string, or boolean) to a variable, the compiler infers the type based on the constant's type. For example:
Go
var x = 42 // x is inferred as int
var y = "hello" // y is inferred as string
- Function Return Types: If you declare a variable and initialize it with the result of a function call, the compiler can infer the type based on the function's return type. For instance:
Go
func GetString() string {
return "Hola!"
}
var message = GetString() // message variable is inferred as string
Key Points to Remember
Type inference in Go is not the same as dynamic typing. The type is still determined at compile time, not during runtime.
Type inference is primarily a convenience for concise variable declarations. It doesn't make Go a dynamically typed language. But "feel" like it.
You can always explicitly declare the type of a variable if you prefer clarity or want to avoid potential type mismatches.
The End
To be honest, i really think this much of information is just overkill but still it's fine. I hope i able to add some value to the developer community.
Again this blog is part of larger blog series : Go (golang) - Beginner
This series will keep going until it teach everything i know about Golang, that i have learnt, currently learning and will learn.
Comment | Like | Subscribe |
If you want to say something | If it helped you! | If you want to continue |
Here are all the links to my social platforms (Twitter\ Linked-In\ Github):
https://hashnode.com/@NavrajSingh
Thanks.