On 17 Jun 2021, at 5:43 pm, Joshua <joshua.oconno...@gmail.com> wrote:

Hello,

I have 2 questions about idiomatic ways to represent optional values,
and variant values in types.

1) I'm modelling a data type which has a field which may or may not be
   there, would most Gophers reach for a pointer here, and use `nil' to
   represent a missing value?

2) Another field of this type contains an "Action", the variants of
   which hold different information. In nonsense code, I want this:

   ,----
   | type EmailAction struct {
   |      Summary string
   |      Decsription string
   |      To string
   |      Attendee person
   |      }
   |
   | type DisplayAction struct {
   |    Description string
   |
   |    }
   |
   | type Event struct {
   |    OptionalField *MyType
   |    Action EmailAction OR DisplayAction
   |    }
   `----


How would you go about modelling this type in Go?  Or alternatively, do
you think trying to use "Type Driven Design" like this is not a good fit
for Go, and rather I should just have a generic set of components and
validate when functions call it.

Personally I prefer the previous, I really like the idea of knowing a
type can't exist in an invalid state! Helps me not have to keep track of
so much in my head.

I will share my thinking for (2):

You could do something like this:

type Action interface {
        # your methods
}

type Event struct {
        OptionalField *MyType
        Action field
}

In your code:

e := Event{..}
Switch e.field.(type):
  case “EmailAction”: do somehting
  case “DisplayAction”: do something else
  default: Invalid action
}



-- 
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an
email to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/8ed722d4-9111-4e23-aa97-f6601f964f0cn%40googlegroups.com
<https://groups.google.com/d/msgid/golang-nuts/8ed722d4-9111-4e23-aa97-f6601f964f0cn%40googlegroups.com?utm_medium=email&utm_source=footer>
.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANODV3kkcuPcx-TqkM36JD9cJQwT4odqkitcHu%2B5j9zyc4cqVw%40mail.gmail.com.

Reply via email to