go-oneof

command module
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2020 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-oneof

This tool is aimed to generate a Go code to partially replicate lacking discriminated unions functionality in Go

Installation

GO111MODULE=on go get github.com/sirkon/go-oneof

How to use it

Need to write a special structure with name staring from oneof (there are further limitations, but they will be reported by the utility itself). Like this:

// node.go file

package node

//go:generate go-oneof node.go

type oneofNode struct {
    Value string
    OperatorSum struct {
        Left  *oneofNode
        Right *oneofNode
    }
}

And run go generate over it

The result will be

package node

//go:generate go-oneof node.go

type oneofNode struct {
	Value       string
	OperatorSum struct {
		Left  *oneofNode
		Right *oneofNode
	}
}

// Node an interface to limit available implementations to emulate discriminated union type
type Node interface {
	isNode()
}

// Value branch of Node
type Value string

func (Value) isNode() {}

// OperatorSum branch of Node
type OperatorSum struct {
	Left  Node
	Right Node
}

func (OperatorSum) isNode() {}

Some notes:

  • type oneofName will generate interface Name with private method isName

  • each field causes an implementation of generated Name

  • comments existed in the source file will disappear in its replacement

  • free comments will stay, but will be moved on the top of the file

  • You may use --pointer or -p call parameter to implement Name of source struct fields over pointer to these structs, not structs themselves, i.e. Node implementation for OperatorSum would be

    func (*OperatorSum) isNode()
    

    in this example

  • This source file may have errors like reference to entities that do not exists. This may work for self reference, but the usage of *oneofNode (change to actual name) is preferable.

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址