Learn about Strings, Numbers, Arrays, Pointers, Type conversions, Slices in Golang
Data types in the Go programming language related to a large framework for defining variables and functions of various sorts. The type of a variable dictates how much storage capacity it takes up and how the stored bit pattern is interpreted.
The types in Go can be classified as follows −
Strings
A string type is a collection of string values. Its value is a byte sequence. Strings are immutable types, which means they can’t be changed after being formed. The string is the predefined string type.
Single line string
str := "Hello"
Multiline string
str := `This is a
Multiline string
in Golang`
Numbers
They’re arithmetic kinds again, used to represent a) integer types or b) floating-point values across the program.
Int
num := 3 // int
Float
num := 3.123 // float64
Complex
num := 3 + 4i // complex128
Byte
num := byte('a') // byte (alias for uint8)
Other types
var u uint = 7 // uint (unsigned)
var p float32 = 22.7 // 32-bit float
Arrays
Arrays have a fixed size.
// var numbers [5]int
numbers := [...]int{0, 0, 0, 0, 0}
Pointers
A pointer holds the memory address of a value. Click here to learn more
The type *T is a pointer to a T value. Its zero value is nil.
var p *int
The & the operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is known as “dereferencing” or “indirecting”. Unlike C, Go has no pointer arithmetic.
package main
import "fmt"
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
Slices
Slice is a lightweight data structure in Go that is more powerful, versatile, and convenient than an array. A slice is a variable-length sequence containing elements of the same kind; multiple components cannot be stored in the same slice.
slice := []int{2, 3, 4}
slice := []byte("Hello")
Type conversions
In computer science, type conversion, typecasting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be converting an integer value into a floating-point value or its textual representation as a string, and vice versa. Wikipedia
i := 2 // int
f := float64(i) //int to float
u := uint(i) // int to uint
Thank you for reading this article, don’t forget to follow me to read more articles like this. You can also share this story with your friends if you find it helpful for others.
_By evolving a Medium partner, you can support me and your other favored writers! _ 👇
Join Medium with my referral link - Harendra Verma
Discussion (0)