optional

package
v1.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2024 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package optional provides a utility type for representing optional values, similar to the concept of Optionals in other programming languages like Java or Rust.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional represents a value that may or may not be present.

Type Parameters:

  • T: The type of the value being wrapped.

Example:

optionalString := Of("hello")
if optionalString.IsPresent() {
    fmt.Println("Value:", optionalString.Value()) // Output: Value: hello
}

emptyOptional := Empty[int]()
fmt.Println("Is present:", emptyOptional.IsPresent()) // Output: Is present: false

func Empty

func Empty[T any]() Optional[T]

Empty creates an Optional with no value.

Returns:

  • An empty Optional.

Example:

emptyOptional := Empty[string]() // Optional[string] with no value

func Of

func Of[T any](v T) Optional[T]

Of creates an Optional containing the provided value.

Parameters:

  • v: The value to wrap in an Optional.

Returns:

  • An Optional containing the provided value.

Example:

optionalInt := Of(42) // Optional[int] containing 42

func (Optional[T]) IsPresent

func (o Optional[T]) IsPresent() bool

IsPresent checks whether the Optional contains a value.

Returns:

  • true if the Optional contains a value, false otherwise.

Example:

optionalString := Of("hello")
fmt.Println(optionalString.IsPresent()) // Output: true

emptyOptional := Empty[string]()
fmt.Println(emptyOptional.IsPresent()) // Output: false

func (Optional[T]) Value

func (o Optional[T]) Value() T

Value retrieves the value stored in the Optional.

Returns:

  • The stored value if present.
  • A zero value of type T if the Optional is empty.

Example:

optionalInt := Of(42)
fmt.Println(optionalInt.Value()) // Output: 42

emptyOptional := Empty[int]()
fmt.Println(emptyOptional.Value()) // Output: 0

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL