Modules, tests and lawsSlide 41 of 86
41.goModules, tests and laws

Importing a Go file

Grammar: import
importPATHasIDENT
import = "import" PATH [ "as" IDENT ] ;

Hive compiles to Go, so a Hive file can call a Go file beside it directly: import ./lib/measures.go. The .go is compulsory, unlike a Hive module's .hive, which is never written, so an import always says which of the two languages it opens.

Every value is deep-copied in both directions. 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 — and a struct keeps its name but lowers its fields' first letters. The Go toolchain reads the signatures; nothing is guessed. 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 as Result<T, Str>; a bare error as Result<Bool, Str>, Ok(true) when it is nil; and no result at all as a func that 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, and the error names 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. If the Go file imports a package from outside Go's standard library, the build fetches it once, with go mod tidy.

lib/measures.go
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
}
main.hive, beside it
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
	}
}