News for hackers. Stuff that matters.
Re:Sum Types in Go by TheHydroImpulse on Friday December 26, 2014 @01:42AM (#8798285)
Sum types are much more direct than other variants in a language that effectively implements them.

For example, in Rust, who's `enum`s are effectively sum types, we can take advantage of the type system while using channels that are well-typed.

https://github.com/servo/servo/blob/master/components/msg/co...

    pub enum Msg {
        ExitMsg,
        FailureMsg(Failure),
        InitLoadUrlMsg(Url),
        LoadCompleteMsg,
        FrameRectMsg(PipelineId, SubpageId, Rect<f32>),
        LoadUrlMsg(PipelineId, LoadData),
        ScriptLoadedURLInIFrameMsg(Url, PipelineId, SubpageId, IFrameSandboxState),
        NavigateMsg(NavigationDirection),
        PainterReadyMsg(PipelineId),
        ResizedWindowMsg(WindowSizeData),
        KeyEvent(Key, KeyState, KeyModifiers),
        /// Requests that the constellation inform the compositor of the title of the pipeline
        /// immediately.
        GetPipelineTitleMsg(PipelineId),
        /// Requests that the constellation inform the compositor of the a cursor change.
        SetCursorMsg(Cursor),
    }

Here we can define a sum type called `Msg` that has various variants. These are the only thing a channel constraint to that type can consume. Each destructing or pattern matching has to cover all possible cases, otherwise it's a compiler error.

This makes it effortless to have complex communication where the data is composed of multiple things, multiple types.

[1] Here's another example of a sum type being used as a messaging type in Servo. [2] Shows pattern matching on all variants and variants of variants, which produces well-typed code.

[1]: https://github.com/servo/servo/blob/master/components/net/re...

[2]: https://github.com/servo/servo/blob/master/components/net/re...

I probably use `enum`s pretty frequently, especially when working with channels. I don't use primitive types-based channels too often come to think of it.

There are no comments on this comment yet.