DEV Community

Cover image for Golang Variable
Jody Septiawan
Jody Septiawan

Posted on • Updated on

Golang Variable

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)
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 )
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Second method:

var name, email, password string = Maya Luna, luna@mail.com, maya123
Enter fullscreen mode Exit fullscreen mode

Top comments (0)