How to Implement an Actor Model in Go
Implement the Actor Model in Go by creating a struct with a channel for message passing and a goroutine that processes messages in a loop.
package main
import (
"fmt"
"time"
)
type Actor struct {
id int
inbox chan string
}
func NewActor(id int) *Actor {
a := &Actor{id: id, inbox: make(chan string, 1)}
go a.run()
return a
}
func (a *Actor) run() {
for msg := range a.inbox {
fmt.Printf("Actor %d received: %s\n", a.id, msg)
}
}
func (a *Actor) Send(msg string) {
a.inbox <- msg
}
func main() {
actor := NewActor(1)
actor.Send("Hello Actor")
time.Sleep(100 * time.Millisecond)
}