Go Maybe

package maybe

type Maybe interface {
    IsJust() bool
    IsNothing() bool
    Map(fn func(v interface{}) interface{}) Maybe
    Extract() interface{}
    OrDefault(v interface{}) interface{}
}

type Nothing struct {
}

type Just struct {
    data interface{}
}

func (m Nothing) of(a interface{}) Maybe {
    return m
}

func (m Nothing) IsNothing() bool {
    return true
}

func (m Nothing) Map(fn func(v interface{}) interface{}) Maybe  {
    return m
}

func (m Nothing) IsJust() bool {
    return false
}

func (m Nothing) Extract() interface{}  {
    panic("Nothing can extract.")
}

func (m Nothing) OrDefault(v interface{}) interface{} {
    return v
}

func (j Just) IsJust() bool  {
    return true
}

func (j Just) IsNothing() bool {
    return false
}

func (j Just) OrDefault(v interface{}) interface{} {
    return j.data
}

func (j Just) Map(fn func(v interface{}) interface{}) Maybe  {
    result := fn(j.data)
    return Just{
        data: result,
    }
}

func (j Just) Extract() interface{} {
    return j.data
}

func Of(v interface{}) Maybe {
    return Just{
        data: v,
    }
}

func Empty() Maybe {
    return Nothing{}
}

使用方法:

func main() {
    a := maybe.Of(12)
    var result maybe.Maybe
    result = a.Map(func(data interface{}) interface{} {
        return data.(int) + 2
    })
    println(result.OrDefault(34).(int))
}