Packages, Modules & Imports
Packages: Go’s module system
Section titled “Packages: Go’s module system”TypeScript uses ES modules (import/export) with npm for packages. Go has a similar concept: packages (a directory of .go files sharing a package declaration) and modules (a collection of packages defined by go.mod, like package.json).
Packages and the package declaration
Section titled “Packages and the package declaration”Every Go file starts with package <name>. Files in the same directory share a package. Executable programs use package main.
// TypeScript: file is automatically a moduleexport function add(a: number, b: number): number { return a + b;}export const PI = 3.14159;// Go: explicit package declarationpackage mathutil
func Add(a, b int) int { return a + b}
const PI = 3.14159Exported vs unexported identifiers
Section titled “Exported vs unexported identifiers”Go’s export system is elegantly simple: capitalise the first letter → exported (public). lowercase → unexported (private to the package). No export keyword needed.
// TypeScript: explicit export keywordexport function PublicFunc() { ... }function privateFunc() { ... } // not exported
export class PublicClass { ... }class InternalClass { ... }// Go: capitalisation IS the export keywordfunc PublicFunc() { ... } // exported — capital Pfunc privateFunc() { ... } // unexported — lowercase p
type PublicStruct struct { ... }type internalStruct struct { ... }go.mod — the package.json equivalent
Section titled “go.mod — the package.json equivalent”// package.json (npm){ "name": "my-app", "version": "1.0.0", "dependencies": { "express": "^4.18.0" }}
// Add dependency:// npm install express// go.modmodule github.com/user/my-app
go 1.22
require ( github.com/gin-gonic/gin v1.9.1)
// Add dependency:// go get github.com/gin-gonic/ginImporting packages
Section titled “Importing packages”// TypeScriptimport { readFileSync } from 'fs';import express from 'express';import { add } from './mathutil';// Goimport ( "os" // stdlib "github.com/gin-gonic/gin" // third-party "github.com/user/app/mathutil" // local package)Try it
Section titled “Try it”package main
import ( "fmt" "strings" "unicode")
func isExported(name string) bool { if name == "" { return false } return unicode.IsUpper(rune(name[0]))}
func main() { names := []string{"Println", "printf", "HTTP", "myHelper", "PublicAPI"} for _, n := range names { status := "unexported" if isExported(n) { status = "EXPORTED" } fmt.Printf("%-12s -> %s\n", n, status) }
s := "go for typescript developers" fmt.Println(strings.ToTitle(s))}Loading Go runtime (first run only, ~8 MB)…