optional

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2023 License: MIT Imports: 2 Imported by: 3

README

Optional

The optional package is a Golang package that provides a type called Option for representing optional values. It allows you to handle scenarios where a value may or may not be present.

Installation

To use the optional package in your Golang project, you can use the following command to install it:

go get github.com/LNMMusic/optional

Usage

Import the optional package in your Go code:

import "github.com/LNMMusic/optional"
Creating an Optional Value

To create an optional value, you can use the Some and None functions.

Some

The Some function creates an optional value with a non-nil inner value.

value := 42
opt := optional.Some(value)
None

The None function creates an optional value with a nil inner value.

opt := optional.None()
Checking if an Optional Value is Some

You can check if an optional value is a Some value by using the IsSome method.

if opt.IsSome() {
    // The optional value is Some
} else {
    // The optional value is None
}
Unwrapping an Optional Value

To retrieve the inner value of a Some optional value, you can use the Unwrap method. It returns the inner value and an error if the optional value is None.

value, err := opt.Unwrap()
if err != nil {
    // Handle the error
} else {
    // Use the inner value
}
Example

Here's an example that demonstrates the usage of the optional package:

package main

import (
	"fmt"

	"github.com/your-username/optional"
)

func main() {
	opt := optional.Some(42)
	if opt.IsSome() {
		value, err := opt.Unwrap()
		if err != nil {
			fmt.Println("Error:", err)
		} else {
			fmt.Println("Value:", value)
		}
	} else {
		fmt.Println("The optional value is None")
	}
}

Error Handling

If you attempt to call the Unwrap method on a None optional value, it will return the ErrUnwrapNone error. You should handle this error appropriately in your code.

JSON Marshalling and Unmarshalling

The Option type in the optional package supports JSON marshalling and unmarshalling. Here are some important points to consider:

  • When unmarshalling JSON into an optional value, make sure to work with a pointer to the optional value. This allows the JSON unmarshalling process to modify the inner value correctly.
  • When marshalling an optional value to JSON, work with a non-pointer value. This ensures that Go's JSON marshalling rules are followed.
Unmarshalling JSON

The UnmarshalJSON method allows you to unmarshal JSON data into an optional value.

data := []byte(`{"Value":42}`)
var opt optional.Option[int]
err := json.Unmarshal(data, &opt)
if err != nil {
    // Handle the error
}
Marshalling JSON

The MarshalJSON method allows you to marshal an optional value to JSON.

opt := optional.Some(42)
data, err := json.Marshal(opt)
if err != nil {
    // Handle the error
} else {
    fmt.Println(string(data))
}

The output of the above code is 42 due to encodes straight forward the inner value of the optional

Please note that marshalling a None optional value will result in null in the JSON output.

License

This package is licensed

under the MIT License. See the LICENSE file for more information.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnwrapNone = errors.New("cannot unwrap None")
)

Functions

This section is empty.

Types

type Option

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

Option is a type that represents an optional value. - value is inmutable - concurrency safe

func None

func None[T any]() Option[T]

None returns an Option with a None value.

func Some

func Some[T any](value T) Option[T]

Constructors Some returns an Option with a Some value.

func (*Option[T]) IsSome

func (o *Option[T]) IsSome() bool

Methods IsSome returns true if the option is a Some value.

func (Option[T]) MarshalJSON

func (o Option[T]) MarshalJSON() (data []byte, err error)

MarshalJSON indicates how to marshal an Option into a json value. marshalling (always work with value) json.Marshal: always sends a non-ptr of the field

  • interface: not always accepts non-ptr > case non-ptr: works > case ptr: does not work (go rules)

cases - method [non-ptr] -> works ()

func (*Option[T]) UnmarshalJSON

func (o *Option[T]) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON indicates how to unmarshal a json value into an Option. unmarshalling (always work with reference) json.Unmarshal: always sends a ptr of the field - interface: always accepts ptr | no matter method receiver

cases - method [ptr-receiver] -> works - method [non-ptr] -> does not work (can't access to the field of &o.Value)

func (*Option[T]) Unwrap

func (o *Option[T]) Unwrap() (t T, err error)

Unwrap returns a copy of the inner value of a Some.

Jump to

Keyboard shortcuts

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