Loading...
Loading...

Go Data Types and Structures Tutorial

Go's type system provides built-in primitive types, composite types, and the ability to create custom types. This tutorial covers Go's fundamental data structures with clear explanations and practical examples.

1. Basic Types

Go has several built-in primitive types that form the building blocks for more complex structures.

var isActive bool = true       // Boolean
var count int = 42            // Platform-dependent integer
var price float64 = 19.99     // 64-bit floating point
var message string = "Hello"  // UTF-8 string
var char rune = 'A'           // Unicode code point (int32 alias)
var rawString string = `Raw\nString` // Raw string literal

Key Characteristics:

  • bool: true/false values
  • int, uint: Size depends on platform (32/64 bit)
  • int8, int16, etc.: Explicitly sized integers
  • float32, float64: IEEE-754 floating point
  • string: Immutable UTF-8 encoded byte sequences
  • rune: Represents a Unicode code point (alias for int32)

Basic Types Quiz

What is the zero value for a boolean in Go?

  • nil
  • false
  • 0

2. Arrays and Slices

Go provides both fixed-size arrays and dynamic slices for sequence data.

// Array (fixed size)
var days [7]string = [7]string{"Mon", "Tue", "Wed"}

// Slice (dynamic array)
primes := []int{2, 3, 5, 7, 11}

// Slice operations
firstTwo := primes[:2]       // [2, 3]
lastThree := primes[2:]      // [5, 7, 11]
middle := primes[1:4]        // [3, 5, 7]

// Appending to slices
primes = append(primes, 13)  // [2, 3, 5, 7, 11, 13]

Key Differences:

  • Arrays: Fixed size, value type (copied when assigned)
  • Slices: Dynamic size, reference type (backed by array)
  • Slices have both length and capacity
  • Use make() to pre-allocate slice capacity

Slices Quiz

What happens when you append beyond a slice's capacity?

  • The program panics
  • Go automatically allocates a larger array
  • Elements are overwritten

3. Maps

Maps are Go's built-in key-value associative data structure.

// Map declaration and initialization
ages := map[string]int{
    "Alice": 25,
    "Bob":   30,
}

// Adding elements
ages["Charlie"] = 28

// Accessing elements
age, exists := ages["Dave"]  // exists=false if key not found

// Deleting elements
delete(ages, "Bob")

// Iterating
for name, age := range ages {
    fmt.Println(name, age)
}

Map Characteristics:

  • Keys must be comparable types (no slices, maps, or functions)
  • Reference type (like slices)
  • Zero value is nil (cannot add to nil map)
  • Use make() or literal syntax for initialization

Maps Quiz

What is returned when accessing a non-existent map key?

  • A runtime error
  • The zero value for the value type
  • A random value

4. Structs

Structs are typed collections of fields that allow you to create custom composite types.

// Struct definition
type Person struct {
    Name string
    Age  int
    Address struct {
        Street string
        City   string
    }
}

// Creating instances
p1 := Person{"Alice", 25, struct{...}{"Main St", "Boston"}}
p2 := Person{
    Name: "Bob",
    Age:  30,
}

// Accessing fields
fmt.Println(p1.Name)

// Anonymous structs
point := struct {
    X, Y int
}{10, 20}

Struct Features:

  • Fields can be any type (including other structs)
  • Uppercase fields are exported (visible outside package)
  • Value type (copied when assigned or passed)
  • Supports composition (but not inheritance)

Structs Quiz

How do you make a struct field accessible outside its package?

  • Add the 'public' keyword
  • Capitalize the first letter
  • Use a special annotation

5. Pointers

Pointers hold memory addresses of values, enabling more efficient data handling.

var x int = 10
ptr := &x  // Get address of x

fmt.Println(*ptr) // Dereference: 10
*ptr = 20         // Modify through pointer
fmt.Println(x)    // 20

// Pointer to struct
p := &Person{Name: "Alice"}
fmt.Println(p.Name)  // Auto-dereferenced

Pointer Rules:

  • & gets the address of a variable
  • * dereferences a pointer
  • No pointer arithmetic (unlike C)
  • Used extensively with structs for mutability
  • Zero value is nil

Pointers Quiz

What is the zero value of a pointer?

  • 0
  • nil
  • An invalid address

6. Interfaces

Interfaces define behavior as sets of method signatures, enabling polymorphism.

// Interface definition
type Speaker interface {
    Speak() string
}

// Implementing types
type Dog struct{}
func (d Dog) Speak() string { return "Woof!" }

type Human struct{}
func (h Human) Speak() string { return "Hello" }

// Interface usage
func greet(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    greet(Dog{})
    greet(Human{})
}

Interface Characteristics:

  • Implicit implementation (no explicit declaration)
  • Can be satisfied by any type with matching methods
  • Empty interface (interface{}) can hold any value
  • Used extensively in Go's standard library

Interfaces Quiz

How does a type implement an interface?

  • By using the 'implements' keyword
  • By implementing all its methods
  • By inheriting from it

7. Advanced Type Features

Go provides several advanced type system features for flexible programming.

// Type aliases
type Celsius float64
type Fahrenheit float64

// Type assertions
var val interface{} = "hello"
str := val.(string)  // Assertion

// Type switches
switch v := val.(type) {
case int:
    fmt.Println("Integer:", v)
case string:
    fmt.Println("String:", v)
}

// Embedded types (composition)
type Writer struct{ io.Writer }

Advanced Features:

  • Type aliases: Create new names for existing types
  • Type assertions: Access concrete type from interface
  • Type switches: Branch based on type
  • Embedding: Achieve composition-based design

Types Quiz

What is Go's primary mechanism for code reuse?

  • Inheritance
  • Composition
  • Mixins
0 Interaction
0 Views
Views
0 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home