Skip to content

Rust inspired Option and Result implementation for Go

License

Notifications You must be signed in to change notification settings

its-felix/shine

Repository files navigation

shine

like metal prior oxidation

Go Reference Go Report

Rust inspired implementation of Option[T] and Result[T] for Go.


Get started

go get github.com/its-felix/shine

Examples

Interoperability with (T, error) receivers

Parsing numbers

// vanilla
v, err := strconv.Atoi("1")
if err != nil {
    v = 1000
}

// shine
v := shine.NewResult(strconv.Atoi("1")).UnwrapOr(1000)

Parsing URLs

func ExampleVanilla() string {
    u, err := url.Parse("https://github.com/")
    if err != nil {
        return ""
    }

    return u.Hostname()
}

func ExampleShine() string {
    return shine.ResMap(shine.NewResult(url.Parse("https://github.com/")), (*url.URL).Hostname).UnwrapOrDefault()
}

Closeable Support

r := shine.NewResult(os.Open("file.txt"))
// will call Close() on the contained value if it implements io.Closer
defer r.Close()

Type switch

r := shine.NewResult(os.Open("file.txt"))
defer r.Close()

switch r := r.(type) {
case Ok[*os.File]:
	f := r.Value()
	// do something with file
	
case Err[*os.File]:
	// handle error
	var pe *os.PathError
	if errors.As(r, &pe) { 
		// handle path error 
	}
}