Skip to content

Instantly share code, notes, and snippets.

@dipankardas011
Last active July 9, 2024 15:51
Show Gist options
  • Save dipankardas011/12aad8d21baeb7e090cc26af565ffc83 to your computer and use it in GitHub Desktop.
Save dipankardas011/12aad8d21baeb7e090cc26af565ffc83 to your computer and use it in GitHub Desktop.
Avoid Null pointer issues in go

used a interface called Option[T any] which helps in defining the types

image

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