This content originally appeared on DEV Community and was authored by Abhinav Pandey
In the last article, I gave a small introduction to programming with Go, where we saw the tiniest possible programs and the general syntax.
Continuing on the syntax, let's take a look at some more syntax and understand how variables are declared in Go.
If you're completely new to Go, please check out the previous article:
Getting started with Go
Abhinav Pandey ・ Nov 20 ・ 3 min read
Variables
Variables are declared using the var
keyword and are used to store values.
The following is an example of a variable declaration.
var name string = "John"
The variable name
is of type string
and is assigned the value John
.
You can also declare multiple variables at once.
var (
name string = "John"
age int = 30
)
You can also declare variables with a type but without an initial value.
var name string
You can also declare multiple variables with a type but without an initial value.
var (
name string
age int
)
Or multiple variables of the same type in a single line.
var name, occupation string
Here, name
and occupation
are of type string
.
** Shorthand declaration of variables **
You can also use the :=
operator to declare and assign a variable at the same time.
name := "John"
Note that the :=
operator is only valid in short variable declarations. You cannot use it outside function bodies.
When using the :=
operator, the variable is declared with the type of the right-hand side expression. The var
keyword is also not required.
** Implicit type declaration **
You can also declare a variable without specifying its type. In this case, the type is inferred from the initial value or a function call.
For example, the following code declares a variable age
of type int
and assigns the value 30
to it.
var age := 30
Or using a function call.
var age := getAge()
This also works for shorthand declarations.
Constants
Constants are declared using the const
keyword. They are used to store values that cannot be changed.
For example, the following code declares a constant PI
and assigns the value 3.14
to it.
const PI = 3.14
Constants can also have implicit type declarations as in the above example.
- They cannot be declared using the
:=
operator. - They cannot be declared without an initial value.
- They cannot accept a function call as an initial value.
- The type of a constant may not be explicitly declared.
Thanks for reading.
This should give you an idea of how variables are declared in Go and how the syntax compares to other programming languages.
Stay tuned for more on Go.
If you want to connect with me, you can find me on Twitter @abh1navv.
This content originally appeared on DEV Community and was authored by Abhinav Pandey
Abhinav Pandey | Sciencx (2021-11-22T13:42:36+00:00) Go Basics: Variables. Retrieved from https://www.scien.cx/2021/11/22/go-basics-variables/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.