Skip to content

Instantly share code, notes, and snippets.

@Borwe
Created September 5, 2024 09:23
Show Gist options
  • Save Borwe/c1e7316f1c8d80473343bcc01fe15577 to your computer and use it in GitHub Desktop.
Save Borwe/c1e7316f1c8d80473343bcc01fe15577 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]) Unwrap(errMsg *string) *T{
if(result.err!=nil){
if errMsg!= nil{
fmt.Errorf(*errMsg)
}else{
fmt.Errorf("ERROR occured", 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 imaginary file
data := Try(os.ReadFile,"fail.go").Unwrap(nil)
fmt.Println(string(*data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment