Different Data Types in GO

Last Updated On Monday 6th Sep 2021

GoLang Data Types

Four types of data.Golang Types.

Basic: Examples include strings, numbers, and Booleans.

Aggregate: Examples include arrays and structs.

Reference: Examples include pointers, slices, functions, and channels.

Interface: An interface is a collection of method signatures.

Using the var keyword: Type-Inferred Variables

The first way to declare a variable is to prefix the variable name with the var keyword and assign it a value.

	package main
import "fmt"
func main() {
   var num1 = 5 // type inferred
   fmt.Println(num1) // 5
	package main
import "fmt"
func main() {
   var num2 int // explicitly typed
   fmt.Println(num2) // 0

Here, num2 is explicitly declared to be an int variable. When you print out its value, you see 0. Variables said without initialization are given their zero value.

Using the short variable declaration operator

Another way to declare and initialize a variable is to use the short variable declaration operator (:=).

	firstName := "Adam Cole"

Here, I’m declaring firstName as a string variable by initializing it to the string “Adam Cole”, all without needing to use the var prefix.

You can also declare and initialize multiple variables (of different types) in a single statement, like below.

	firstName, lastName, age := "Adam Cole", "Henry", 22

You can declare them like below also.

	var (
 firstName string = "Adam Cole"
 lastName string = "Henry"
 age int = 22

Working With Strings

  • A string can contain special characters (such as \n or \t)
	address := "66 Perry Street\nWest Village\nWashington"

A pair of backticks enclose a raw string .It can span multiple lines, and special characters have no meaning in it.

	address := `"66 Perry Street
West Village

Interpolating strings

	ID := 5
name := "Alice"

//  But you can’t do something like this
out := name + ", your ID number is:" + ID

This is because ID is an integer, and you can’t simply directly concatenate string and integer values. To fix this, you can convert the integer variable value to a string and then join them.

  • You can use the strconv package’s Atoi() function to try to convert the string into an integer value.

  • Atoi stands for ASCII to integer. Itoa, on the other hand, stands for Integer to ASCII.

	out := name + ", your ID number is:" + strconv.Itoa(ID)