On Thu, Jun 17, 2021 at 9:43 AM 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?
>

I don't know about "most Gophers" (it's hard to generalize), but I would.


>
> 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?
>

Either using an interface, or by having two pointer-fields and only setting
one.
Depending on the details, it might also be worth considering inverting the
relationship:

type Event struct {
    OptionalField *MyType
    …
}

type EmailEvent struct {
    Event
    Summary string
    …
}

type DisplayEvent struct {
    Event
    Description string
    …
}


>   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.
>
> --
> 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/CAEkBMfH_QpEzMhnuXLtJPQMFhoO%2B%3DYJ2w1uro%2Bx4G-5TmY5FPw%40mail.gmail.com.

Reply via email to