Skip to content

Instantly share code, notes, and snippets.

@Borwe
Last active September 5, 2024 10:31
Show Gist options
  • Save Borwe/f4052661a4c9272dfa6ba96989c2f905 to your computer and use it in GitHub Desktop.
Save Borwe/f4052661a4c9272dfa6ba96989c2f905 to your computer and use it in GitHub Desktop.
Failure handling in go zig rust hybrid style combo
package main
import (
"fmt"
"os"
)
type Result [T any] struct {
err error
result *T
}
func (result Result[T]) OrElse(fn func() T) *T{
ans := fn()
return &ans
}
func (result Result[T]) Unwrap(errMsg *string) *T{
if(result.err!=nil){
if errMsg!= nil{
fmt.Fprintf(os.Stderr,*errMsg)
}else{
fmt.Fprintf(os.Stderr,"ERROR occured: %s\n", result.err)
}
os.Exit(-1)
}
return result.result
}
func Try[T any,R any](fn func(T) (R,error), take T) Result[R]{
data, err:= fn(take)
if(err!=nil){
return Result[R]{
result: nil,
err: err,
}
}
return Result[R]{
result: &data,
err: err,
}
}
func main(){
//reading this file
// when functions expect multiple values, pass as tuple
//data := Try(os.ReadFile,("fail.go")).Unwrap(nil)
//fmt.Println(string(*data))
// when functions expect single values, pass as tuple
//data := Try(os.ReadFile,"fail.go").Unwrap(nil)
//fmt.Println(string(*data))
//reading imaginary file should fail
//failureMsg := "LOLOLOLOL.txt file not exists"
//Try(os.ReadFile, "LOLOLOLOL.txt").Unwrap(nil)
data := Try(os.ReadFile, "LOLOLOLOL.txt").OrElse(func() []byte {
return []byte("lol")
})
fmt.Println(string(*data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment