Composite Types in Go: Arrays, Slices, Maps, Structs, JSON, and Templates
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] 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) } 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] 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] 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 Checking Key Existence value, exists := m["orange"] if exists { fmt.Println("Value:", value) } else { fmt.Println("Key not found") } 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) Struct Literals p := Person{"Bob", 25} // Shorthand initialization 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 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 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"} 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("Hello, {{.}}")) tmpl.Execute(os.Stdout, "World") 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(` GitHub Issues Issues for {{.Repo}} {{range .Issues}} {{.Title}} - {{.State}} {{end}} `)) 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) } 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

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]
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)
}
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]
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]
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
Checking Key Existence
value, exists := m["orange"]
if exists {
fmt.Println("Value:", value)
} else {
fmt.Println("Key not found")
}
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)
Struct Literals
p := Person{"Bob", 25} // Shorthand initialization
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
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
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"}
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("Hello, {{.}}
"))
tmpl.Execute(os.Stdout, "World")
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(`
GitHub Issues
Issues for {{.Repo}}
{{range .Issues}}
- {{.Title}} - {{.State}}
{{end}}
`))
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)
}
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.