Skip to content

zachcoleman/simple-monads

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

simple-monads

A Rust-inspired implementation of Option and Result types using generic structs.

Requires: Go >= 1.18 (generics added).

Examples

value, err := MyFallibleFunction()
res := Result(value, err)
if res.IsOk(){
    ...
}
value, err := MyFallibleFunction()
res := Result(value, err)
value = res.UnwrapOr(value2)

Option constructor accepts pointers:

maybe := Option(ReturnsPtr())
if maybe.IsSome(){
    ...
}
maybe := Option(ReturnsPtr())
value := maybe.UnwrapOr(myDefaultValue)

Use OptionType or ResultType for type defintions such as function returns:

func MyOptionalInt() OptionType[int]{
    ...
}
func MyFallibleInt() ResultType[int]{
    ...
}

Supports Scan interface from database/sql and implements a ToDB helper method:

db := Result(sql.Open("sqlite3", ":memory:")).Unwrap()
defer db.Close()

Result(db.Exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value INTEGER)")).Unwrap()
Result(db.Exec("INSERT INTO test (value) VALUES (1)")).Unwrap()

var i *int64 // sql driver requires int64
opt := Option(i)
_ = db.QueryRow("SELECT value FROM test WHERE id = 1").Scan(&opt)
fmt.Println(opt.Some()) // prints 1
db := Result(sql.Open("sqlite3", ":memory:")).Unwrap()
defer db.Close()

Result(db.Exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value INTEGER)")).Unwrap()

var i *int64 // sql driver requires int64
opt := Option(i)
insert := Result(db.Exec(
	"INSERT INTO test (value) VALUES (?)",
	Result(opt.ToDB()).Unwrap(),
))

See tests for a few more examples.

About

Option and Result types

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages