In Golang, there are 2 ways to declare variables, namely by specifying the data type and also without specifying the data type. Both of these methods are valid and serve the same purpose.
1. Variable Declaration with Data Type
Manifest typing is commonly used when declaring variables with the data type explicitly mentioned. Here's an example:
var fullName string = “Maya Luna”
var gender string
gender = “female”
fmt.Printf(“Name: %s”, fullName)
fmt.Printf(“Gender: %s”, gender)
2. Variable Declaration with the 'var' Keyword
In the example above, variable declaration uses the "var" keyword, which is used to create a new variable.
The structure of using the "var" keyword is as follows:
var <nama_variabel> <tipe_data>
var <nama_variabel> <tipe_data> = <nilai>
3. Variable Declaration without Data Type
In addition to the concept of Manifest typing, Golang also has the concept of Type interface, which is the declaration of variables whose data type is determined by their value. With this approach, there is no need to write "var."
var fullName string = “Maya Luna”
gender := “female”
fmt.Printf(“Name: %s”, fullName)
fmt.Printf(“Gender: %s”, gender )
When applying the concept of Manifest typing, use the ":=" operator when assigning a value to a variable.
4. Declaration of Multiple Variables
Golang supports the declaration of multiple variables at once. You can do this by adding a comma "," between the variables.
First method:
var name, email, password string
name, email, password = “Maya Luna”, “luna@mail.com”, “maya123”
Second method:
var name, email, password string = “Maya Luna”, “luna@mail.com”, “maya123”
Top comments (0)