DEV Community

Walid LAGGOUNE
Walid LAGGOUNE

Posted on • Edited on

Composite Types in Go: Arrays, Slices, Maps, Structs, JSON, and Templates

Hi, my name is Walid, a backend developer who’s currently learning Go and sharing my journey by writing about it along the way.
Resource :

  • The Go Programming Language book by Alan A. A. Donovan & Brian W. Kernighan
  • Matt Holiday go course

Composite Types in Go: Arrays, Slices, Maps, Structs, JSON, and Templates

Go (Golang) provides several powerful composite types, including arrays, slices, maps, and structs, which allow efficient data handling and organization. In this article, we will explore these types in depth, along with JSON handling and HTML templates, culminating in a practical example that fetches GitHub issues and displays them using an HTML template.

Arrays in Go

An array is a fixed-size sequence of elements of the same type.

var arr [5]int // An array of 5 integers
arr[0] = 10 // Assigning a value
fmt.Println(arr) // Output: [10 0 0 0 0]
Enter fullscreen mode Exit fullscreen mode

Arrays have fixed sizes, making them inflexible for dynamic data handling.

Iterating Over an Array

for i, v := range arr {
    fmt.Println("Index:", i, "Value:", v)
}
Enter fullscreen mode Exit fullscreen mode

Slices in Go

Slices are dynamically sized, flexible views of arrays.

s := []int{1, 2, 3, 4, 5} // Slice initialization
fmt.Println(s[1:4]) // Output: [2 3 4]
Enter fullscreen mode Exit fullscreen mode

Slices have length and capacity, and can be extended efficiently.

The append Function

The append function dynamically resizes slices.

s = append(s, 6, 7, 8)
fmt.Println(s) // Output: [1 2 3 4 5 6 7 8]
Enter fullscreen mode Exit fullscreen mode

Maps in Go

Maps provide a key-value data structure.

m := make(map[string]int)
m["apple"] = 3
m["banana"] = 5
fmt.Println(m["apple"]) // Output: 3
Enter fullscreen mode Exit fullscreen mode

Checking Key Existence

value, exists := m["orange"]
if exists {
    fmt.Println("Value:", value)
} else {
    fmt.Println("Key not found")
}
Enter fullscreen mode Exit fullscreen mode

Structs in Go

A struct is a composite type that groups multiple fields together.

type Person struct {
    Name string
    Age  int
}
p := Person{Name: "Alice", Age: 30}
fmt.Println(p)
Enter fullscreen mode Exit fullscreen mode

Struct Literals

p := Person{"Bob", 25} // Shorthand initialization
Enter fullscreen mode Exit fullscreen mode

Comparing Structs

Structs can be compared if all fields are comparable.

type Point struct {
    X, Y int
}
p1 := Point{1, 2}
p2 := Point{1, 2}
fmt.Println(p1 == p2) // Output: true
Enter fullscreen mode Exit fullscreen mode

Struct Embedding and Anonymous Fields

Go supports embedding structs for composition.

type Address struct {
    City, Country string
}
type Employee struct {
    Name    string
    Address // Embedded struct (anonymous field)
}
e := Employee{Name: "John", Address: Address{"New York", "USA"}}
fmt.Println(e.City) // Accessing embedded field directly
Enter fullscreen mode Exit fullscreen mode

JSON Handling in Go

The encoding/json package provides JSON serialization and deserialization.

import (
    "encoding/json"
    "fmt"
)
type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
user := User{"Alice", "alice@example.com"}
jsonData, _ := json.Marshal(user)
fmt.Println(string(jsonData)) // Output: {"name":"Alice","email":"alice@example.com"}
Enter fullscreen mode Exit fullscreen mode

Text and HTML Templates in Go

Go’s html/template package provides safe HTML rendering.

import (
    "html/template"
    "os"
)
tmpl := template.Must(template.New("test").Parse("<h1>Hello, {{.}}</h1>"))
tmpl.Execute(os.Stdout, "World")
Enter fullscreen mode Exit fullscreen mode

Fetching GitHub Issues and Displaying in an HTML Template

This example fetches issues from a GitHub repository and displays them in an HTML template.

package main

import (
    "encoding/json"
    "fmt"
    "html/template"
    "net/http"
)

type Issue struct {
    Title string `json:"title"`
    State string `json:"state"`
}

type Issues struct {
    Items []Issue `json:"items"`
}

func fetchGitHubIssues(repo string) ([]Issue, error) {
    url := fmt.Sprintf("https://api.github.com/search/issues?q=repo:%s", repo)
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var issues Issues
    if err := json.NewDecoder(resp.Body).Decode(&issues); err != nil {
        return nil, err
    }
    return issues.Items, nil
}

func handler(w http.ResponseWriter, r *http.Request) {
    repo := "golang/go"
    issues, err := fetchGitHubIssues(repo)
    if err != nil {
        http.Error(w, "Failed to load issues", http.StatusInternalServerError)
        return
    }

    tmpl := template.Must(template.New("issues").Parse(`
    <html>
    <head><title>GitHub Issues</title></head>
    <body>
        <h1>Issues for {{.Repo}}</h1>
        <ul>
            {{range .Issues}}
                <li>{{.Title}} - {{.State}}</li>
            {{end}}
        </ul>
    </body>
    </html>`))

    data := struct {
        Repo   string
        Issues []Issue
    }{repo, issues}

    tmpl.Execute(w, data)
}

func main() {
    http.HandleFunc("/", handler)
    fmt.Println("Server started at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Fetches GitHub issues using http.Get.
  • Decodes JSON into a Go struct.
  • Uses html/template to render issues dynamically.
  • Runs a web server to serve the data.

Conclusion

Go’s composite types (arrays, slices, maps, and structs) allow efficient data organization. With JSON and templates, Go excels in building web applications. The example provided demonstrates Go’s simplicity and power for fetching and rendering external data dynamically.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay