Skip to content

Commit

Permalink
Improve gox examples
Browse files Browse the repository at this point in the history
  • Loading branch information
icza committed Oct 10, 2024
1 parent 12b2ad7 commit 8720f50
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ name: Go

on:
push:
branches: [ main ]
branches: [ "main" ]
pull_request:
branches: [ main ]
branches: [ "main" ]

jobs:

Expand Down
42 changes: 38 additions & 4 deletions gox/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,58 @@ package gox_test

import (
"fmt"
"image"
"os"
"strconv"
"time"

. "github.com/icza/gox/gox"
)

func Example() {
// Mimicing the ternary operator:
for _, age := range []int{10, 20} {
state := If(age < 18, "child", "adult")
fmt.Printf("[If] Age: %d, state: %s\n", age, state)
}

// Pointers to non-zero values"
b, i, s := Ptr(true), Ptr[uint](1), Ptr("hi")
fmt.Printf("[Ptr] b: %t, i: %d, s: %s\n", *b, *i, *s)

// Safely dereference pointers:
var nilPtr *string
fmt.Printf("[Deref] s: %q, nilPtr: %q\n", Deref(s), Deref(nilPtr))

// Pass multiple return values to variadic functions:
now := time.Date(2020, 3, 4, 0, 0, 0, 0, time.UTC)
fmt.Printf("Year: %d, month: %d, day: %d\n",
fmt.Printf("[Wrap] Year: %d, month: %d, day: %d\n",
Wrap(now.Date())...)

// Using one of multiple return values:
fmt.Println("[First-Third] Time coordinates:", image.Point{
X: First(now.Date()),
Y: Third(now.Date()),
})

// First non-zero of many values:
hostName := ""
fmt.Println("[Coalesce] Host name:", Coalesce(hostName, os.Getenv("HOST"), "localhost"))

// Quick "handling" of error:
n, err := strconv.Atoi("3")
Pie(err)
fmt.Println("Parsed:", n)
fmt.Println("[Pie] Parsed:", n)
fmt.Println("[Must] Parsed:", Must(strconv.Atoi("4")))

// Output:
// Year: 2020, month: 3, day: 4
// Parsed: 3
// [If] Age: 10, state: child
// [If] Age: 20, state: adult
// [Ptr] b: true, i: 1, s: hi
// [Deref] s: "hi", nilPtr: ""
// [Wrap] Year: 2020, month: 3, day: 4
// [First-Third] Time coordinates: (2020,4)
// [Coalesce] Host name: localhost
// [Pie] Parsed: 3
// [Must] Parsed: 4
}

0 comments on commit 8720f50

Please sign in to comment.