Go: Data Types
I am following this youtube course link to learn Go programming and will document all the learning in this series of blog posts.
There are different categories of type in Go:
- Basic type: Numbers, strings, and booleans come under this category.
- Aggregate type: Array and structs come under this category.
- Reference type: Pointers, slices, maps, functions, and channels come under this category.
- Interface type
Types are case-sensitive. Variable type should be known in advance.
Basic data types in Go:
- string
- int
- float
- complex
- bool
- byte
To read more on data types please refer here
Code examples
package main
import "fmt"
func main() {
// string data type
var name string = "ben"
fmt.Println(name)
fmt.Printf("Variable is of type: %T\n", name)
// bool data type
var flag bool = true // false
fmt.Println(flag)
fmt.Printf("Variable is of type: %T\n", flag)
// small int data type
var sint uint8 = 10 // max val can be 255
fmt.Println(sint)
fmt.Printf("Variable is of type: %T\n", sint)
// int data type
var int_val int = 10 // max val can be 255
fmt.Println(int_val)
fmt.Printf("Variable is of type: %T\n", int_val)
// float data type
var float_val float32 = 10.123456789 // max val can be 255
fmt.Println(float_val)
fmt.Printf("Variable is of type: %T\n", float_val)
// default value and type of int
var int_val_defailt int
fmt.Println(int_val_defailt)
fmt.Printf("Variable is of type: %T\n", int_val_defailt)
// default value for string data type
var default_str string
fmt.Printf("Default value of string data type variable is: %s ", default_str)
fmt.Println()
// data type can also be inferred implicitly
var isClosed = false
fmt.Println(isClosed)
fmt.Printf("Variable is of type: %T\n", isClosed)
// we cannot change the data type of a variable
// isClosed = "hello" will result in compile time
// no var style using walrun operator
numUsers := 100
fmt.Println(numUsers)
fmt.Printf("Variable is of type: %T\n", numUsers)
// this operator only works inside a method
// const variable
const MOD = 10000
fmt.Println(MOD)
fmt.Printf("Variable is of type: %T\n", MOD)
}
Output
ben
Variable is of type: string
true
Variable is of type: bool
10
Variable is of type: uint8
10
Variable is of type: int
10.123457
Variable is of type: float32
0
Variable is of type: int
Default value of string data type variable is:
false
Variable is of type: bool
100
Variable is of type: int
10000
Variable is of type: int