Data type, variable and value in Golang

(2 minutes for reading)

Go is a statically typed programming language. This means that variables always have a specific type and that type cannot change. The keyword var is used for declaring variables of a particular data type. Here is the syntax for declaring variables

var name_of_variable [data type] = [value]
var x int = 1
var y float = 19.9

var myName string = "thaibao"
var isGoodWebsite = true

Go has various value types including strings, integers, floats, booleans, etc. Here are a few basic examples.


Try an example to practice with variable:

package main

import "fmt"

func main() {
	var x int = 100
	fmt.Println("x = ", x)

	var y = 19.9
	fmt.Println("y = ", y)

	var myName = "thaibao"
	fmt.Println("myName = ", myName)

	var isGoodWebsite = true
	fmt.Println("isGoodwebsite = ", isGoodWebsite)
}

OK, what happen in demo. I declared x with int(integer data type) and print out console with format “x = value of x”, and step by step with some example, we have results on screen.


Easy? Now, we have some thing more fun. An advance feature of “var” keyword. “var” can support to declares 1 or more variables.

func main() {
	var x1, x2, x3 int = 21, 6, 1987
	fmt.Println("x1 = ", x1)
	fmt.Println("x2 = ", x2)
	fmt.Println("x3 = ", x3)
}

Run and get below result

MORE:
 If you are using an initializer expression for declaring variables, you can omit the type using short variable declaration as shown here:

func main() {
	// this is a short declaring variable and value, omit data type because you knew what it is
	thisAStringVariableMyEmail := "thaibao56@gmail.com"
	fmt.Println("I will print this varible for you:", thisAStringVariableMyEmail)
}

View on github


PrevNext