Built-in Data Types

Just like any other programming languages, Go has a number of built-in data types:

Basic Data types

  • bool
  • string
  • (u)int, (u)int8, (u)int16, (u)int32, (u)int64, uintptr
    • u means unsigned
    • uintptr means pointer
  • byte (8 bits)
  • rune (32 bits), similar to char in C
  • float32, float64
  • complex64, complex128

Go is one of few languages that support complex numbers which is widely used in computational applications.

1
2
3
4
func complex_num() {
c := 3 + 4i //with 4i Go can deduct that c is a complex number
fmt.Println(cmplx.Abs(c))
}

We could use the complex number to play with the beautiful Euler formula

1
2
3
4
5
func euler(){
fmt.Println(cmplx.Pow(math.E, 1i*math.Pi) + 1)
// alternatively, we could use cmplx.Exp
fmt.Println(cmplx.Exp(1i*math.Pi) + 1)
}

It will print out results below, which is really close to 0.

1
2
(0+1.2246467991473515e-16i)
(0+1.2246467991473515e-16i)

The trailing imaginary number is due to the float precision, we could get rid of it by using fmt.Printf

1
2
3
4
func euler() {
fmt.Printf("%.3f\n", cmplx.Pow(math.E, 1i*math.Pi)+1)
fmt.Printf("%.3f\n", cmplx.Exp(1i*math.Pi)+1)
}

It will print out the following

1
2
(0.000+0.000i)
(0.000+0.000i)

Type Conversion

There’s no implicit type conversion in Go, all convertions are explicit.
The example below will report type errors during compilation.

1
2
3
4
5
6
func triangle() {
var a, b int = 3, 4
var c int
c = math.Sqrt2(a*a + b*b)
fmt.Println(c)
}

In stead, we have to explicitly claim a, b, c are floats

1
2
3
4
5
6
func triangle() {
var a, b = 3, 4
var c float64
c = math.Sqrt(float64(a*a + b*b))
fmt.Println(c)
}