https://github.com/eminarican/safetypes
Rust like result and option implementation for golang
https://github.com/eminarican/safetypes
go golang option option-type optional optional-type result result-type rust
Last synced: 6 months ago
JSON representation
Rust like result and option implementation for golang
- Host: GitHub
- URL: https://github.com/eminarican/safetypes
- Owner: eminarican
- License: gpl-3.0
- Created: 2022-03-18T03:04:30.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-08-30T09:55:16.000Z (about 3 years ago)
- Last Synced: 2024-06-21T06:40:13.421Z (over 1 year ago)
- Topics: go, golang, option, option-type, optional, optional-type, result, result-type, rust
- Language: Go
- Homepage:
- Size: 31.3 KB
- Stars: 33
- Watchers: 2
- Forks: 2
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# safetypes
Rust like result and option implementation for golangjust a reminder, option type is ready for (un)marshalling, mongodb and rethinkdb so feel free to use it with ^^
## Examples
```go
import safe "github.com/eminarican/safetypes"
```### Option
```go
func checkUnwrap(opt safe.Option[int]) {
if opt.IsSome() {
println(opt.Unwrap())
} else {
panic("poor option :(")
}
}
```
```go
func checkUnwrapOr(opt safe.Option[int]) {
println(opt.UnwrapOr(10))
}
```
```go
func retrunOption(some bool) (opt safe.Option[int]) {
if some {
return opt.Some(7)
}
return opt.None()
}
```
```go
type Test struct {
Field safe.Option[int]
}func jsonMarshal(t Test) {
res := safe.AsResult(json.Marshal(s))
if res.IsOk() {
// if some: "Test{Field: 7}"
// if none: "Test{Field: {}}"
println(res.Unwrap())
} else {
panic(res.Error())
}
}
```### Result
```go
func checkUnwrap(res safe.Result[int]) {
if res.IsOk() {
println(res.Unwrap())
} else {
panic(res.Error())
}
}
```
```go
func retrunResult(some bool) (res safe.Result[int]) {
if some {
return res.Ok(7)
}
return res.Err("some fancy error msg")
}
```### Note
Error and None methods usable as structless but it doesn't infere types so instead of using `safetypes.None[T]()` and `safetypes.Err[T]("")` you could use them as how in examples above