philipbohun.com

Glojure by Example: Embedding

A Go program can host Glojure. Import pkg/glj for its side effects so the runtime is initialized, then runtime.ReadEval evaluates source and returns the value. This is how an application keeps its core in Go and loads Clojure for configuration, policy, or plugins.

package main

import (
    "fmt"

    _ "github.com/glojurelang/glojure/pkg/glj"
    "github.com/glojurelang/glojure/pkg/runtime"
)

func main() {
    result := runtime.ReadEval(`
        (defn factorial [n]
          (loop [i n
                 acc 1]
            (if (<= i 1)
              acc
              (recur (dec i) (* acc i)))))
        (factorial 5)
    `)
    fmt.Println(result)
}

The call returns a Go value. Here that value is the integer 120, and fmt.Println prints it. The other direction, calling a Go function from Clojure inside the same process, uses the package interop from the earlier pages, or a var you install with glj.Var before evaluating.

From the module that contains main.go, run the package.

$ go run .
120

Back to the list of examples.