Created
February 15, 2025 22:25
-
-
Save racsoraul/f57a0419dcddd44db7e9ff1773ba04af to your computer and use it in GitHub Desktop.
AST with Go's interfaces dynamic dispatching.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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