used a interface called Option[T any] which helps in defining the types
Created
September 26, 2023 06:09
-
-
Save dipankardas011/12aad8d21baeb7e090cc26af565ffc83 to your computer and use it in GitHub Desktop.
Avoid Null pointer issues in go
This file contains 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" | |
type Class interface { | |
Hello() | |
} | |
type Demo struct { | |
Name string | |
Roll int | |
} | |
func (d *Demo) Hello() { | |
fmt.Println(d.Name, d.Roll) | |
} | |
// Option is a custom type that represents either a value or no value (None). | |
type Option[T any] interface { | |
// isOption() | |
} | |
// func (s Some[T]) isOption() {} | |
// func (n None[T]) isOption() {} | |
type Some[T any] struct { | |
Value T | |
} | |
type None[T any] struct{} | |
func NewSome[T any](value T) Option[T] { | |
return Some[T]{Value: value} | |
} | |
func NewNone[T any]() Option[T] { | |
return None[T]{} | |
} | |
func main() { | |
var obj Option[Class] = None[Class]{} | |
switch o := obj.(type) { | |
case Some[Class]: | |
fmt.Println("some value") | |
o.Value.Hello() | |
case None[Class]: | |
fmt.Println("nil pointer found") | |
default: | |
fmt.Println("Invalid type") | |
} | |
obj = Some[Class]{Value: &Demo{Name: "dipankar", Roll: 20000}} | |
switch o := obj.(type) { | |
case Some[Class]: | |
fmt.Println("some value") | |
o.Value.Hello() | |
case None[Class]: | |
fmt.Println("nil pointer found") | |
default: | |
fmt.Println("Invalid type") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment