A library that provides Go Generics friendly "optional" features.

go-optional .github/workflows/check.yml codecov

A library that provides Go Generics friendly "optional" features.

Synopsis

true fmt.Printf("%v\n", some.IsNone()) // => false v, err := some.Take() fmt.Printf("err is nil: %v\n", err == nil) // => err is nil: true fmt.Printf("%d\n", v) // => 123 mapped := optional.Map(some, func (v int) int { return v * 2 }) fmt.Printf("%v\n", mapped.IsSome()) // => true mappedValue, _ := some.Take() fmt.Printf("%d\n", mappedValue) // => 246 ">
some := optional.Some[int](123)
fmt.Printf("%v\n", some.IsSome()) // => true
fmt.Printf("%v\n", some.IsNone()) // => false

v, err := some.Take()
fmt.Printf("err is nil: %v\n", err == nil) // => err is nil: true
fmt.Printf("%d\n", v) // => 123

mapped := optional.Map(some, func (v int) int {
    return v * 2
})
fmt.Printf("%v\n", mapped.IsSome()) // => true

mappedValue, _ := some.Take()
fmt.Printf("%d\n", mappedValue) // => 246
false fmt.Printf("%v\n", none.IsNone()) // => true _, err := none.Take() fmt.Printf("err is nil: %v\n", err == nil) // => err is nil: false // the error must be `ErrNoneValueTaken` mapped := optional.Map(none, func (v int) int { return v * 2 }) fmt.Printf("%v\n", mapped.IsNone()) // => true ">
none := optional.None[int]()
fmt.Printf("%v\n", none.IsSome()) // => false
fmt.Printf("%v\n", none.IsNone()) // => true

_, err := none.Take()
fmt.Printf("err is nil: %v\n", err == nil) // => err is nil: false
// the error must be `ErrNoneValueTaken`

mapped := optional.Map(none, func (v int) int {
    return v * 2
})
fmt.Printf("%v\n", mapped.IsNone()) // => true

and more detailed examples are here.

Docs

GoDoc

Tips

  • it would be better to deal with an Option value as a non-pointer because if the Option value can accept nil it becomes worthless

Current Status

Currently (at the moment: Nov 18, 2021), go 1.18 has not been released yet, so if you'd like to try this, please use the tip runtime.
Of course, the new runtime version hasn't been released yet so this library has the possibility to change the implementation as well.

Known Issues

The runtime raises a compile error like "methods cannot have type parameters", so Map(), MapOr(), Zip() and ZipWith() has been providing as functions. Basically, it would be better to provide them as the methods, but currently, it compromises with the limitation.

Author

moznion ([email protected])

Owner
moznion
I usually don't read e-mail. If you want to tell me something (e.g. "response an issue just now!"), please send me a message through twitter:@moznion.
moznion
Comments
  • Support `OrElse`

    Support `OrElse`

    Simple usecase:

    optionalResult := db.call()
    
    
    # as-is
    optionalResult.IfNone(func() {
      optionalResult = db.someOtherCall()
    }
    return optionalResult
    
    
    # to-be
    return optionalResult.OrElse(db.someOtherCall)
    

    rust's Option supports this: https://doc.rust-lang.org/std/option/enum.Option.html#method.or_else

    Thanks for your work!

  • Support `#OrElse()` that supports to return the `Option` value according to the actual value existence

    Support `#OrElse()` that supports to return the `Option` value according to the actual value existence

    Usage example is here: https://github.com/moznion/go-optional/pull/21/files#diff-533b7626d1981e5b4f6500e692dfffc48f5cfd3d078c24bf831abbeb4bf5fccc Close #20

  • Update module github.com/stretchr/testify to v1.8.1

    Update module github.com/stretchr/testify to v1.8.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | github.com/stretchr/testify | require | patch | v1.8.0 -> v1.8.1 |


    Release Notes

    stretchr/testify

    v1.8.1

    Compare Source


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

  • Update module github.com/stretchr/testify to v1.8.0

    Update module github.com/stretchr/testify to v1.8.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | github.com/stretchr/testify | require | minor | v1.7.2 -> v1.8.0 |


    Release Notes

    stretchr/testify

    v1.8.0

    Compare Source

    v1.7.5

    Compare Source

    v1.7.4

    Compare Source

    v1.7.3

    Compare Source


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

  • Update module github.com/stretchr/testify to v1.7.1

    Update module github.com/stretchr/testify to v1.7.1

    WhiteSource Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | github.com/stretchr/testify | require | patch | v1.7.0 -> v1.7.1 |


    Release Notes

    stretchr/testify

    v1.7.1

    Compare Source


    Configuration

    📅 Schedule: At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by WhiteSource Renovate. View repository job log here.

  • Support two value factory methods: `FromNillable()` and `PtrFromNillable()`

    Support two value factory methods: `FromNillable()` and `PtrFromNillable()`

    These methods accept the nillable pointer value as an argument and make the Optional[T] type value.

    FromNillable()

    If the given value is not nil, this returns Some[T] value with doing value-dereference. On the other hand, if the value is nil, this returns None[T].

    example:

    num := 123
    
    some := FromNillable[int](&num)
    fmt.Printf("%v\n", some.IsSome()) // => true
    fmt.Printf("%v\n", some.Unwrap()) // => 123
    
    none := FromNillable[int](nil)
    fmt.Printf("%v\n", none.IsSome()) // => false
    fmt.Printf("%v\n", none.Unwrap()) // => 0 (the default value of int)
    

    PtrFromNillable()

    If the given value is not nil, this returns Some[*T] value without doing value-dereference. On the other hand, if the value is nil, this returns None[*T].

    example:

    num := 123
    
    some := PtrFromNillable[int](&num)
    fmt.Printf("%v\n", some.IsSome())  // => true
    fmt.Printf("%v\n", *some.Unwrap()) // => 123 (NOTE: it needs doing dereference)
    
    none := PtrFromNillable[int](nil)
    fmt.Printf("%v\n", none.IsSome()) // => false
    fmt.Printf("%v\n", none.Unwrap()) // => nil
    
  • Support `omitempty` option on JSON marshaling

    Support `omitempty` option on JSON marshaling

    This pull request makes it support the omitempty option on JSON marshaling. If the property has that option and the value is None[T], it omits that property from serialized JSON string.

    example:

    type JSONStruct struct {
    	OmitemptyVal Option[string] `json:"omitemptyVal,omitempty"` // this should be omitted
    }
    jsonStruct := &JSONStruct{OmitemptyVal: None[string]()}
    marshal, err := json.Marshal(jsonStruct)
    if err != nil {
    	return err
    }
    fmt.Printf("%s\n", marshal) // => {}
    
  • Update module go to 1.19

    Update module go to 1.19

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | go (source) | golang | minor | 1.18 -> 1.19 |


    Release Notes

    golang/go

    v1.19.0


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

  • Support `FlatMap` functions:

    Support `FlatMap` functions:

    • FlatMap[T, U any](option Option[T], mapper func(v T) Option[U]) Option[U]
    • FlatMapOr[T, U any](option Option[T], fallbackValue U, mapper func(v T) Option[U]) U
    • FlatMapWithError[T, U any](option Option[T], mapper func(v T) (Option[U], error)) (Option[U], error)
    • FlatMapOrWithError[T, U any](option Option[T], fallbackValue U, mapper func(v T) (Option[U], error)) (U, error)
  • Support Option[T]#Unwrap() method

    Support Option[T]#Unwrap() method

    Unwrap returns the value regardless of Some/None status. If the Option value is Some, this method returns the actual value. On the other hand, if the Option value is None, this method returns the default value according to the type.

  • Add new `If*` method onto Option struct

    Add new `If*` method onto Option struct

    • func (o Option[T]) IfSome(f func(v T))
    • func (o Option[T]) IfSomeWithError(f func(v T) error) error
    • func (o Option[T]) IfNone(f func())
    • func (o Option[T]) IfNoneWithError(f func() error) erro
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Other Branches

    These updates are pending. To force PRs open, click the checkbox below.

    • [ ] Update codecov/codecov-action action to v3

    Detected dependencies

    github-actions
    .github/workflows/check.yml
    • actions/setup-go v3
    • actions/checkout v3
    • golangci/golangci-lint-action v3
    • codecov/codecov-action v2
    gomod
    go.mod
    • go 1.19
    • github.com/stretchr/testify v1.8.1

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
Go-generics-simple-doubly-linked-list - A simple doubly linked list implemented using generics (Golang)

Welcome to Go-Generics-Simple-Doubly-Linked-List! Hi, This repository contains a

Jun 30, 2022
Package truthy provides truthy condition testing with Go generics
Package truthy provides truthy condition testing with Go generics

Truthy Truthy is a package which uses generics (Go 1.18+) to create useful boolean tests and helper functions. Examples // truthy.Value returns the tr

Nov 11, 2022
Go Library for Competitive Programming with Generics

Go Library for Competitive Programming with Generics Go used to be a difficult language to use for competitive programming. However, with the introduc

Dec 21, 2022
Extended library functions using generics in Go.

Just few extended standard library functions for Golang using generics.

Dec 16, 2021
Utility library that uses Go generics mechanism

golang-generics-util Utility library that explores Go generics (1.18) xsync Sync

Dec 11, 2022
Use is a go utility library using go1.18 generics

use use is a go utility library using go1.18 generics created by halpdesk 2022-01-22 use/slice Map updates a slice by applying a function to all membe

Jan 22, 2022
redis-util business-friendly encapsulation of redis operations, such as the common cache set get operation

redis-util 方便业务使用的redis操作封装,比如常见的缓存set get操作, 一行代码搞定,不像开源库需要写好多行 使用方法

Oct 22, 2021
Deduplicated and GC-friendly string store

This library helps to store big number of strings in structure with small number of pointers to make it friendly to Go garbage collector.

Nov 10, 2021
Code Generation for Functional Programming, Concurrency and Generics in Golang

goderive goderive derives mundane golang functions that you do not want to maintain and keeps them up to date. It does this by parsing your go code fo

Dec 25, 2022
Experiments with Go generics

generics Quick experiments with Go generics algebra, a generic square root function for float, complex and and rational. future, a concurrent cache ("

Dec 31, 2022
Example code for Go generics

go-generics-example Example code for Go generics. Usage $ go build -gcflags=-G=3 Requirements Go 1.17 or later Advertise Go 言語にやってくる Generics は我々に何をも

Dec 30, 2022
Collection of unusual generics usecases in Go

Unusual Generics Type parameters or Generics in Go designed to reduce boilerplate for container data types like lists, graphs, etc. and functions like

Dec 14, 2022
experimental promises in go1.18 with generics

async go a prototype of "promises" in go1.18. note: this is just an experiment used to test alternate patterns for dealing with asynchronous code in g

Dec 23, 2022
Go 1.18 generics use cases and examples

Go 1.18 generics use cases What are generics? See Type Parameters Proposal. How to run the examples? As of today, gotip is the simplest way to run the

Jan 10, 2022
Functional tools in Go 1.18 using newly introduced generics

functools functools is a simple Go library that brings you your favourite functi

Dec 5, 2022
Experimenting with golang generics to implement functional favorites like filter, map, && reduce.

funcy Experimenting with golang generics to implement functional favorites like filter, map, && reduce. 2021-12 To run the tests, you need to install

Dec 29, 2021
A collection of functional operators for golang with generics

fn fn is a collection of go functional operators with generics Getting Started P

Jul 8, 2022
Benchmarks to compare Go Generics

This is a collection of various sorts implemnted both as []int only and as const

Dec 8, 2022
CDN-like in-memory cache with shielding, and Go 1.18 Generics

cache CDN-like, middleware memory cache for Go applications with integrated shielding and Go 1.18 Generics. Usage package main import ( "context" "

Apr 26, 2022