Skip to content

Instantly share code, notes, and snippets.

@racsoraul
Created February 15, 2025 22:25
Show Gist options
  • Save racsoraul/f57a0419dcddd44db7e9ff1773ba04af to your computer and use it in GitHub Desktop.
Save racsoraul/f57a0419dcddd44db7e9ff1773ba04af to your computer and use it in GitHub Desktop.
AST with Go's interfaces dynamic dispatching.
package main
import (
"fmt"
)
func main() {
result := multiply(Value{2}, add(Value{3}, Value{4})).Evaluate()
fmt.Println(result)
}
type Expression interface {
Evaluate() int
}
type Value struct{ Value int }
func (l Value) Evaluate() int { return l.Value }
type Binary struct {
Left Expression
OperatorToken rune
Right Expression
}
func (b Binary) Evaluate() int {
switch b.OperatorToken {
case '+':
return b.Left.Evaluate() + b.Right.Evaluate()
case '*':
return b.Left.Evaluate() * b.Right.Evaluate()
default:
panic("Invalid operator")
}
}
func add(a, b Expression) Expression {
return Binary{a, '+', b}
}
func multiply(a, b Expression) Expression {
return Binary{a, '*', b}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment