Golang: Basic Types

By Xah Lee. Date: . Last updated: .

Basic Types

Go's basic types are

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.

Rune Type

Golang: Rune

Find a Value's Type

fmt.Printf("%T\n", val) → print a value's type.

package main

import "fmt"

func main() {

    var nn = 3
    var ff = 3.123

    // print their types
    fmt.Printf("%T\n", nn) // int
    fmt.Printf("%T\n", ff) // float64
}

Type conversions

type(v) → converts the value v to the type type, where type is the same keyword as the type declaration, e.g. int, string, bool, etc.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var i int = 42
    var f = float64(i)
    fmt.Println(reflect.TypeOf(f)) // float64
}

Convert String to Byte Slice

String to byte slice:

var xBytes = []byte(xString)

Byte slice to string:

var xString = string(xBytes)

Note: string and byte slice are pretty much the same, except string cannot be changed. everytime a string is changed, it's a new string.

package main

import "fmt"

var t = `long big text`

func main() {
    // convert string to byte slice
    var bs = []byte(t)

    fmt.Printf("%T\n", bs)
}

[see Golang: Slice]

Reference

The Go Programming Language Specification - The Go Programming Language#Types

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. Rune
  8. String as Chars
  9. Variable
  10. Zero Value
  11. Constant
  12. If Then Else
  13. Switch/Case
  14. Loop
  15. Basic Types
  16. Array
  17. Slice
  18. Map
  19. Struct
  20. Function
  21. regexp
  22. Read File
  23. Write to File
  24. Walk Dir
  25. Check File Exist
  26. System Call
  27. Get Script Path
  28. Pointer
  29. Defer
  30. Random Number

Examples

  1. match any regexp
  2. Validate Links
  3. Generate Sitemap

Reference

  1. Go Spec