used a interface called Option[T any] which helps in defining the types
Last active
July 9, 2024 15:51
-
-
Save dipankardas011/12aad8d21baeb7e090cc26af565ffc83 to your computer and use it in GitHub Desktop.
Avoid Null pointer issues in go
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 | |
type Option[T any] struct { | |
valid bool | |
value T | |
} | |
func Some[T any](value T) Option[T] { | |
return Option[T]{ | |
valid: true, | |
value: value, | |
} | |
} | |
func None[T any]() Option[T] { | |
return Option[T]{} | |
} | |
func (m Option[T]) IsSome() bool { | |
return m.valid | |
} | |
func (m Option[T]) IsNone() bool { | |
return !m.valid | |
} | |
func (m Option[T]) Unwrap() T { | |
if m.IsNone() { | |
panic("Unwrap called on None") | |
} | |
return m.value | |
} | |
func (m Option[T]) UnwrapOr(defaultValue T) T { | |
if m.IsNone() { | |
return defaultValue | |
} | |
return m.value | |
} | |
func Something(x string) Option[string] { | |
if x == "" { | |
return None[string]() | |
} | |
return Some(x) | |
} | |
func main() { | |
switch Something("Hello") { | |
case Some("Hello"): | |
println("got val:", Something("Hello").Unwrap()) | |
case None[string](): | |
println("Handled") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment