Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sug0/go-union
Unions in go (?!)
https://github.com/sug0/go-union
go tagged type union
Last synced: 2 days ago
JSON representation
Unions in go (?!)
- Host: GitHub
- URL: https://github.com/sug0/go-union
- Owner: sug0
- Created: 2019-09-05T18:28:11.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-03-18T01:06:12.000Z (almost 3 years ago)
- Last Synced: 2024-11-02T09:04:40.544Z (about 2 months ago)
- Topics: go, tagged, type, union
- Language: Go
- Size: 13.7 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-union
This package implements C-like unions in Go, by messing with `unsafe`
code.The API to work with them is somewhat ergonomic, utilizing
Go's interfaces to cast around the different types.## Who would use this package?
A madman. Use the `unsafe` package directly, honestly.
## API documentation
Find it at godoc:
* [Unsafe unions](https://godoc.org/github.com/sug0/go-union)
* [Tagged unions](https://godoc.org/github.com/sug0/go-union/tagged)
* [Auto generated wrappers over native Go types](https://godoc.org/github.com/sug0/go-union/types)## Example usage
```go
package mainimport (
"fmt"tagged "github.com/sug0/go-union/tagged"
types "github.com/sug0/go-union/types"
)func main() {
// This struct will describe our union;
// the fields need to be exported, because
// the package typechecks the values at runtime
// with reflection...
myEnum := struct {
Float32 *types.Float32
Int32 *types.Int32
}{}// Initialize the union with a value.
intOrFloat, err := tagged.InitWith(myEnum, func(u *tagged.Union) {
var f types.Float32
u.CastTo(&f)
*f.Ptr = 343.12
})
if err != nil {
panic(err)
}// Debug contents.
switch intOrFloat.Kind() {
default:
panic("We're not a float32!")
case types.KindFloat32:
fmt.Println("I'm a float32!")
fmt.Printf("%#v\n", intOrFloat)
}// Update content.
var i types.Int32
intOrFloat.CastTo(&i)
*i.Ptr = 45// Debug contents.
switch intOrFloat.Kind() {
default:
panic("We're not an int32!")
case types.KindInt32:
fmt.Println("I'm an int32!")
fmt.Printf("%#v\n", intOrFloat)
}
}
```