Importing a Go file
Grammar: import
Hive compiles to Go, so a Go file beside a Hive one can be called from it directly: import ./lib/measures.go. The .go is compulsory — the opposite of a Hive module's .hive, which is never written — so an import never leaves you wondering which of the two languages you are about to open.
Every value is deep-copied in both directions, which is the point of the boundary: a Go function can sort the slice it was handed, keep it, or write through it later, and none of that reaches the Hive value it came from. That is also why an imported Go function arrives as a func.
Only what Go exports is reachable. A function is reached with its first letter lowered — Grams is measures.grams — a struct keeps its name and lowers its fields' first letters, and the signatures are read by the Go toolchain rather than guessed at. What crosses:
string,int,float64,bool,[]T,[][]string, a map with a scalar key — whose keys arrive sorted, since a Go map has no order — and a struct the file exports;(T, error), which arrives asResult<T, Str>; a bareerrorasResult<Bool, Str>,Ok(true)when it isnil; and no result at all as afuncthat answers nothing.
A pointer, a channel, an interface, a function value, a variadic parameter, int64, a fixed-size array, an unexported or embedded struct field, or a type from another package is refused, naming the parameter it could not take. Every exported function in the file has to cross, called or not, and the first one that cannot is the one reported. A Go file that imports a package from outside Go's standard library makes the build fetch it, once, with go mod tidy.
package measures
import (
"fmt"
"strings"
)
// Every field of this struct crosses the boundary, so the whole struct does.
type Weight struct {
Grams int
Label string
}
// Exported, so Hive reaches it with its first letter lowered: measures.grams.
func Grams(w Weight) int {
return w.Grams
}
// Go's way of reporting failure is Hive's: (T, error) is Result<T, Str>.
func Parse(s string) (Weight, error) {
if !strings.HasSuffix(s, "g") {
return Weight{}, fmt.Errorf("%q does not end in g", s)
}
return Weight{Grams: len(s) * 100, Label: s}, nil
}import ./lib/measures.go
proc main(): void {
tool := measures.Weight(899, "Hive tool")
echo measures.grams(tool)
parsed := measures.parse("450g")
if parsed is Result.Ok(w) {
echo "{w.label}: {w.grams}"
} else if parsed is Result.Error(why) {
echo why
}
}