Comment

Comment by hmmdar

Another way to do `Option` without pointers could be similar to the following with a struct with two members.

  type Option[T any] struct {
      v T
      isSet bool
  }
  
  func NewOption[T any](v T) Option[T] {
      return Option[T]{
          v: v,
          isSet: true,
      }
  }
  
  func (o Option[T]) Get() (v T) {
      if !o.isSet {
          return v
      }
      return o.v
  }
  
  func (o Option[T]) IsSet() bool { return o.isSet }

With this pattern you're able to use `Option` as a value without pointers.

  var o Option[int32]
  
  o = NewOption(int32(1))
  
  fmt.Println("value:", o.Get())
  fmt.Println("is set:", o.IsSet())
Alternative separate `Get` and `IsSet` methods, is to combine them into one, similar to map look up pattern.

  func (o Option[T]) Get() (v T, isSet bool) {
      if !o.isSet {
          return v, false
      }
      return o.v, true
  }
  
  var o Options[int32]
  v, ok := o.Get() // zero, false
  
  o = NewOption(int32(1))
  v, ok = o.Get() // 1, true
parent hmmdar 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton