Skip to content

Instantly share code, notes, and snippets.

@angch
Created June 24, 2020 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angch/bfd98f1cb0bd5577d81abdd8fbc5ef14 to your computer and use it in GitHub Desktop.
Save angch/bfd98f1cb0bd5577d81abdd8fbc5ef14 to your computer and use it in GitHub Desktop.
quick hack attempting sumtypes in Go
package main
import "log"
// enum ShapeKind { Square, Rectangle, Circle };
// struct Shape {
// int centerx;
// int centery;
// enum ShapeKind kind;
// union {
// struct { int side; }; /* Square */
// struct { int length, height; }; /* Rectangle */
// struct { int radius; }; /* Circle */
// };
// };
// int getSquareSide(struct Shape* s) {
// assert(s->kind == Square);
// return s->side;
// }
// void setSquareSide(struct Shape* s, int side) {
// s->kind = Square;
// s->side = side;
// }
type ShapeKind int
const Square ShapeKind = iota
const Rectangle = iota
const Circle = iota
type Shape struct {
centerx, centery int
}
type ShapeInterface interface {
GetShape() Shape
}
type ShapeSquare struct {
Shape
side int
}
type ShapeRectangle struct {
Shape
length, height int
}
type ShapeCircle struct {
Shape
radius int
}
func (s ShapeSquare) GetShape() Shape {
return s.Shape
}
func (s ShapeCircle) GetShape() Shape {
return s.Shape
}
func (s ShapeRectangle) GetShape() Shape {
return s.Shape
}
func (s ShapeSquare) GetSide() int {
return s.side
}
func (s *ShapeSquare) SetSide(side int) {
s.side = side
}
func main() {
shapes := make([]ShapeInterface, 0)
shapes = append(shapes, ShapeSquare{Shape: Shape{0, 0}, side: 1})
shapes = append(shapes, ShapeCircle{Shape: Shape{0, 0}, radius: 1})
shapes = append(shapes, ShapeRectangle{Shape: Shape{0, 0}, length: 1, height: 1})
log.Printf("%+v\n", shapes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment