Go - Understand how to use packages, variables, and functions in Go (I) - Basic data types

Source: Understand how to use packages, variables, and functions in Go

Basic data types

Integer

var integer int = 123

// But there are other integer types
var integer8 int8 = 127
var integer16 int16 = 32767
var integer32 int32 = 2147483647
var integer64 int64 = 9223372036854775807

A rune is simply an alias for int32 data type. It’s used to represent a Unicode character (or a Unicode code point)

rune := 'G'
fmt.Println(rune) # 71 unicode character for G

Floating-point numbers

var float32 float32 = 2147483647
var float64 float64 = 9223372036854775807

Booleans

var featureFlag bool = true

Strings

To initialize a string variable, you need to define its value within double quotation marks (“). Single quotation marks (‘) are used for single characters (and for runes, as we saw in a previous section)

var firstName string = "John"
lastName := "Doe"

Escape characters:

  • \n for new lines
  • \r for carriage returns
  • \t for tabs
  • ' for single quotation marks
  • " for double quotation marks
  • \ for backslashes

E.g:

fullName := "John Doe \t(alias \"Foo\")\n"
fmt.Println(fullName) # John Doe        (alias "Foo")

Default values

All data types have a default value when you don’t initialize a variable:

  • 0 for int types (and all of its subtypes, like int64)
  • +0.000000e+000 for float32 and float64 types
  • false for bool types
  • An empty value for string types

Type conversions

Between numbers:

var integer16 int16 = 127
int32(integer16) # it's a int32

String an int

Use the strconv package:

  • Atoi (string to int)
  • Itoa (int to string)
package main

import (
  "strconv"
)

func main() {
  i, err := strconv.Atoi("-42")
  s := strconv.Itoa(-42)
}