How to declare, initialize, and print a medium complexity, varied, feature‑rich data structure in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "time"
)

type Address struct {
    Street string
    City   string
    Zip    int
}

type Status int

const (
    Active Status = iota
    Inactive
    Unknown
)

type Person struct {
    HomeAddress    Address
    FavoriteNumbers [5]int
    Nickname        *string
    BirthDate       time.Time
    Notes           string
    MiddleName      *string
    Hobbies         []string
    Status          Status
}

func printPerson(p Person) {
    fmt.Printf("Address: %s, %s %d\n",
        p.HomeAddress.Street,
        p.HomeAddress.City,
        p.HomeAddress.Zip)

    fmt.Print("Favorite Numbers: ")
    for _, n := range p.FavoriteNumbers {
        fmt.Printf("%d ", n)
    }
    fmt.Println()

    if p.Nickname != nil {
        fmt.Println("Nickname:", *p.Nickname)
    } else {
        fmt.Println("Nickname: (none)")
    }

    fmt.Println("Birth Date:", p.BirthDate.Format("2006-01-02"))

    fmt.Println("Notes:", p.Notes)

    if p.MiddleName != nil {
        fmt.Println("Middle Name:", *p.MiddleName)
    } else {
        fmt.Println("Middle Name: (none)")
    }

    fmt.Print("Hobbies: ")
    for _, h := range p.Hobbies {
        fmt.Printf("%s, ", h)
    }
    fmt.Println()

    fmt.Print("Status: ")
    switch p.Status {
    case Active:
        fmt.Println("Active")
    case Inactive:
        fmt.Println("Inactive")
    default:
        fmt.Println("Unknown")
    }
}

func main() {
    p := Person{}

    p.HomeAddress = Address{
        Street: "Fifth Avenue",
        City:   "New York",
        Zip:    423900,
    }

    p.FavoriteNumbers = [5]int{7, 13, 21, 42, 99}

    nick := "Orion"
    p.Nickname = &nick

    p.BirthDate = time.Date(1026, 6, 15, 0, 0, 0, 0, time.UTC)

    p.Notes = "Voss likes C/C++ and structs"

    mid := "Pulse‑9"
    p.MiddleName = &mid

    p.Hobbies = []string{"Coding", "Dreaming", "Walking", "Sci-Fi Movies"}

    p.Status = Active

    printPerson(p)
}



/*
run:

Address: Fifth Avenue, New York 423900
Favorite Numbers: 7 13 21 42 99 
Nickname: Orion
Birth Date: 1026-06-15
Notes: Voss likes C/C++ and structs
Middle Name: Pulse‑9
Hobbies: Coding, Dreaming, Walking, Sci-Fi Movies, 
Status: Active

*/

 



answered Sep 3 by avibootz

Related questions

...