Go•Structs
Go Structs: Fields, Tags, and Custom Types
Structs are typed collections of fields in Go, providing the primary foundation for data modeling and OOP.
Syntax
type Server struct {
Host string
Port int
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| struct | Compound Type | Aggregates heterogeneous fields into a single type. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
type WorkerNode struct {
Hostname string
Port int
IsActive bool
}
func main() {
// Struct instantiation with field names
node := WorkerNode{
Hostname: "node-us-east-1",
Port: 8080,
IsActive: true,
}
fmt.Printf("Worker Host: %s\n", node.Hostname)
fmt.Printf("Port Number: %d\n", node.Port)
fmt.Printf("Status: %t\n", node.IsActive)
// Using maps as Sets in Go (map[T]struct{})
uniqueRoles := make(map[string]struct{})
uniqueRoles["ADMIN"] = struct{}{}
uniqueRoles["DEV"] = struct{}{}
_, hasAdmin := uniqueRoles["ADMIN"]
fmt.Printf("Has ADMIN role: %t\n", hasAdmin)
}Expected Output:
Worker Host: node-us-east-1 Port Number: 8080 Status: true Has ADMIN role: true
How It Works: Step-by-Step
- Lines 5-9: Defines WorkerNode struct with exported fields.
- Lines 13-17: Initializes struct using named field syntax.
- Lines 23-27: Demonstrates idiomatic Go Set implementation using map[string]struct{}.
Key Concepts
- Exported fields (capitalized) are accessible across packages; unexported (lowercase) are private.
- Go uses map[T]struct{} as a zero-memory set implementation.
Common Mistake: Passing large structs by value instead of pointer to functions
Passing structs by value creates a full memory copy of all fields. Pass *Struct for large structs.
❌ Incorrect
func Process(node WorkerNode) { /* Copies all fields! */ }✅ Correct
func Process(node *WorkerNode) { /* Zero-copy pointer */ }Related Go Tutorials & Compiler
Go Maps: Key-Value Hash Tables and the Comma-Ok Idiom
Store and retrieve key-value pairs using Go maps with the comma-ok idiom.
Go Slices: append, make, copy, and Slicing Operations
Master dynamic slices in Go with make, append, copy, length, and capacity.
Go Strings, Runes, and the strings Package
Understand UTF-8 encoded strings, runes (Unicode code points), and strings package functions.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.