Skip to content

Provides a type for working with optional variables, fields in structures, functions and database models.

License

Notifications You must be signed in to change notification settings

kazhuravlev/optional

Repository files navigation

optional

Go Reference License Build Status Go Report Card codecov Mentioned in Awesome Go

Type-safe optional values for Go - marshal/unmarshal to/from JSON, YAML, SQL and more.

Installation

go get github.com/kazhuravlev/optional

Quick Start

package main

import (
	"encoding/json"
	"fmt"
	"github.com/kazhuravlev/optional"
)

type User struct {
	Name      string               `json:"name"`
	AvatarURL optional.Val[string] `json:"avatar_url,omitempty"`
}

func main() {
	// JSON with optional field
	data := []byte(`{"name": "Alice", "avatar_url": "https://example.com/avatar.jpg"}`)
	
	var user User
	json.Unmarshal(data, &user)
	
	// Check if value exists
	if avatarURL, ok := user.AvatarURL.Get(); ok {
		fmt.Printf("Avatar URL: %s\n", avatarURL)
	}
	
	// Or use a default
	url := user.AvatarURL.ValDefault("https://example.com/default.jpg")
	fmt.Printf("URL with default: %s\n", url)
}

Key Features

  • Type-safe: Generic implementation prevents runtime type errors
  • Zero value friendly: Missing values are not mistaken for zero values
  • Multiple formats: Works with JSON, YAML, SQL, and custom marshalers
  • Simple API: Intuitive methods like Get(), Set(), HasVal(), and Reset()

API Overview

var opt optional.Val[string]

// Set a value
opt.Set("hello")

// Check and get
if val, ok := opt.Get(); ok {
    fmt.Println(val) // "hello"
}

// Get with default
val := opt.ValDefault("default") // "hello"

// Reset to empty
opt.Reset()

// Convert to pointer (nil if empty)
ptr := opt.AsPointer() // *string

About

Provides a type for working with optional variables, fields in structures, functions and database models.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages