DEV Community

indiewebdev
indiewebdev

Posted on

Golang Notes - 6

Data Types

predeclared types - builtin types

  • basic types: integers , floating point numbers, complex numbers, byte, rune, string, boolean

  • int8, int16, int32, int64,
    int -> alias for int32 or int64 based on platform

var i8 int8 = -128 // [-128, 127]
var ui16 uint16 = 65535 // [0, 65535]
Enter fullscreen mode Exit fullscreen mode
  • uint8, uint16, uint32, uint64, uint -> alias for uint32 or uint64 based on platform
  • float32, float64
  • complex64, complex128
comp1 := complex(1, 2) // constructor way
comp2 := 1 + 2i    // second way to init
Enter fullscreen mode Exit fullscreen mode
  • byte -> alias for uint8
  • rune -> alias for int32 represents a Unicode code point
var r rune = 'f'
fmt.Printf("%T\n", r)
// int32
Enter fullscreen mode Exit fullscreen mode
  • bool type - pre-defined constants true and false
  • string type

    • unicode chars written enclosed by double-quote
  • composite types : array, slice, map, struct, pointer, function, interface, channel

  • array type

    • fixed length
    • must contain single type
var nums = [3]int{1,2,3}
Enter fullscreen mode Exit fullscreen mode
  • slice type
    • dynamic length, can shrink or grow
    • must contain same type
var cities = []string{"Istanbul", "Tokyo"}
Enter fullscreen mode Exit fullscreen mode
  • map type
    • unordered group of elements of single type
    • indexed by a set of unique keys
balances := map[string]float64{
"USD": 2000.3,
"EUR": 3000.4,
}
Enter fullscreen mode Exit fullscreen mode
  • struct type
    • consist of named elements, fields
    • each field has name and type
    • allow user to define custom type
type Person struct {
  name string
  age int
}
Enter fullscreen mode Exit fullscreen mode
  • pointer type
    • stores memory address
    • uninitialized, default value nil
var x int = 1
ptr := &x // address of x
fmt.Printf("%T\n", ptr)
fmt.Println(ptr)
fmt.Println(*ptr) // access value
// *int
// 0xc000012028
// 1
Enter fullscreen mode Exit fullscreen mode
  • function type
func f() {}
fmt.Printf("%T\n", f)
// func()
Enter fullscreen mode Exit fullscreen mode
  • interface type
  • channel type
    • provides mechanism for concurrent communication
c := make(chan int) // unbuffered
c2 := make(chan int, 2) // buffered
fmt.Printf("%T\n", c)
// chan int
Enter fullscreen mode Exit fullscreen mode

Top comments (0)