Created
September 5, 2024 09:23
-
-
Save Borwe/c1e7316f1c8d80473343bcc01fe15577 to your computer and use it in GitHub Desktop.
Failure handling in go zig rust hybrid style combo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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