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. String Backslash Escape
  8. Rune
  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. String as Chars
  22. regexp
  23. Read File
  24. Write to File
  25. Walk Dir
  26. Check File Exist
  27. System Call
  28. Get Script Path
  29. Pointer
  30. Defer
  31. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec