Code Monkey home page Code Monkey logo

gost's Introduction

GoST - Go Safe Types

Gost is a Golang package that provides two safe generic types, Option and Result, inspired by Rust's Option and Result types. These types are designed to simplify working with optional and error-handling scenarios, reducing the need for excessive nil and error checks.

Option Type

The Option type represents an optional value and includes various methods for handling optional values.

Usage Examples

Returning Options

func maybe() gost.Option[int] {
    if /* some condition here */ {
        return gost.Some(10)
    } 

    return gost.None[int]()
}

val := maybe()

Wrapping Existing Functions

slice := []int{1, 2, 3, 4, 5}
target := 4

v := gost.AsOption(slices.BinarySearch(slice, target))

Checking Option State

if val.IsSome() {
    // Option has a value
}

if val.IsNone() {
    // Option is empty
}

Extracting Values

v := val.Unwrap()
v := val.UnwrapOr(10)
v := val.UnwrapOrElse(func() int { return calculateDefaultValue() })
v := val.UnwrapOrZero()

Panic, Fatal, Exit

v := val.UnwrapOrPanic("Value is required!")
v := val.UnwrapOrLogFatal("Fatal: Value is required!")
v := val.UnwrapOrExit(1)

Result Type

The Result type represents a value or an error and includes methods for handling successful results and errors.

Usage Examples

Creating Results

func risky() gost.Result[int] {
    v, err := /* some risky function call */
    if err != nil {
        return gost.Ok(v)
    } 

    return gost.Error[int](err)
}

val := risky()

Wrapping Existing Functions

val := gost.AsResult(os.ReadFile("non-existent-file.txt"))

Checking Result State

if val.IsOk() {
    // Result is successful
}

if val.IsError() {
    // Result is an error
}

Extracting Values And Errors

v := val.Unwrap()
err := val.UnwrapError()
v := val.UnwrapOr("Default")
v := val.UnwrapOrElse(func() string { return calculateDefaultString() })
v := val.UnwrapOrZero()

Panic, Fatal, and Exit

v := val.UnwrapOrPanic()
v := val.UnwrapOrLogFatal()
v := val.UnwrapOrExit(1)
v := val.UnwrapOrDynamicExit(func(err error) int { return calculateExitCode(err) })

"Pattern Matching"

You can also handle Result and Options using a sort of pattern matching syntax:

val := gost.AsOption(slices.BinarySearch([]int{1, 2, 3, 4, 5}, 10)).
        OnSome(func(v *int) *int { return v }).
        OnNone(func() int { return -1 })

val := gost.AsResult(os.ReadFile("non-existent-file.txt")).
        OnOk(func(v *[]byte) *[]byte { return v }).
        OnError(func(e error) []byte { return []byte{} })

This is syntax is very limited in his extensibility due to the lack of generics on golang struct methods, thus it only comes handy when you need some side effects while extracting the option or result inner value.

func respondSuccess[T any](w http.ResponseWriter, v T) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(v)
    return v
}

func respondNotFound[T any](w http.ResponseWriter, v T) T {
    w.WriteHeader(http.StatusNotFound)
    W.Write("")
    return v
}

func userHandler(w http.ResponseWriter, req *http.Request) {
    gost.AsOption(db.FetchUser(4)).
        OnSome(func(v *int) *int { return respondSuccess(w, v) }).
        OnNone(func() int { return respondNotFound(w, v) })
}

gost's People

Contributors

twoojoo avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.