Go
Practical Go notes on modules, packages, imports and build commands, followed by language behavior, value copying, RPC, goroutines and testing.
- Written
- Published
- Updated
Go
Go module
module
A module = a collection of packages versioned together.
Create a module on current workfolder.
go mod init <module name>
Then it will create go.mod in current like this
module 6.5840
go 1.22
require github.com/anishathalye/porcupine v1.0.3
It defines your project’s identity and dependencies.
If current workfolder has go.mod file, you can use go mod tidy to adds missing deps (if imports exist) and removes unused deps.
And these module will be downloaded in $GOPATH/pkg/mod
go mod tidy
package
Every .go file starts with a package declaration:
package main
In Go, a package = a collection of Go files in the same directory with the same package name.
- Special rule: If the package name is
main, the Go toolchain knows it’s meant to produce an executable program (not just a library). Amainpackage must define amain()function:
And we can use other package as library package.
Package path
A package path is the string you use in the import statement to refer to a package. It tells the compiler where to find the package’s code. It usually corresponds to:
-
A module path + folder path (for your own code).
-
A fully qualified URL (for third-party modules on the internet).
Rules for imports
-
Standard library: You can import packages like
fmt,math,net/httpdirectly by their package names. -
Local packages:
- Must be inside your module folder (the folder with
go.modat the root). - It will try to find a go.mod from nearest parent folder, and using such folder as module root.
- Import path =
module path + relative path to the package.
Example:
/myproject/go.mod -> module myproject /myproject/util/math/math.go -> package mathThen in another file in the module:
import "myproject/util/math" - Must be inside your module folder (the folder with
-
Third-party packages (modules):
-
Use the module path from
go.modof that module. -
Must run
go get <module-path>orgo installto download it.module 6.5840 go 1.22.2 require github.com/anishathalye/porcupine v1.0.3import "github.com/anishathalye/porcupine"
-
NOTE:
The package name (declared in package xyz) does not have to match the folder name, but it’s conventional to match it.
The import path must match the folder path relative to the module root, or the full module path for external packages.
You cannot import a file directly; you always import the package.
In Go, having many packages in the same folder is not allowed. Here's the detailed reasoning and implications:
All .go files in a single folder must declare the same package name.
The same package
Variable, function can be accessed each other in two different files with the same package, if they are exported(i.e., they are start with UPPERCASE letter).
Across module import
If my module 6.5840 want to use debvg module, I need to tell Go where to find debug locally in go.mod in module `6.5840:
module 6.5840
go 1.22
require debug v0.0.0
replace debug => ../debug
require debug v0.0.0→ a fake version (since it’s local).replace debug => ../debug→ points Go to your local folder.
Go command
Go build
Go build will compile and link all .go files in current folder and create an executable file for that.
Go has several build modes:
| Mode | Output |
|---|---|
default | executable binary |
c-shared | shared library (.so) callable from C |
plugin | Go plugin (.so file) that can be dynamically loaded |
shared | Go shared library used by other Go programs |
when run like go build -buildmode=plugin ../mrapps/wc.go
1.Go compiles wc.go into machine code.
2.Packages and functions are turned into exported symbols inside a .so file.
3.Later, another Go program can load it at runtime:
import "plugin"
p, err := plugin.Open("wc.so")
if err != nil { ... }
mapSymbol, err := p.Lookup("Map")
reduceSymbol, err := p.Lookup("Reduce")
Lookuplets you get references to the exported functions or variables inwc.so.
Go run
go build + run such executable file immediately + delete it.
Go basic
Difference between c
Since go have auto memory management and GC.
Returning a local variable is valid
func f() *int {
x := 10
return &x
}
Closure
func MakeCounter() func() int {
count := 0
return func() int { // returning a closure
count++
return count
}
}
Even though count is a local variable of MakeCounter, the returned closure can still access it after MakeCounter has returned.
Value copy
Always by value in Go.
-
For structs → full copy.
-
For pointers → copy of address (so both point to same thing).
-
For reference types (slice, map, chan, func) → copy of small header (contains pointer), so underlying data is shared.
e.g.
type Point struct {
X, Y int
}
func change(p Point) {
p.X = 99
}
func main() {
a := Point{1, 2}
change(a)
fmt.Println(a) // {1 2}, unchanged
}
When you pass a, Go copies the entire struct into the parameter.
So the function gets its own copy. Changes don’t affect the caller’s value.
RPC
RPC stands for Remote Procedure Call.
It’s a way for a program to call a function (a "procedure") that lives on another computer (or another process) as if it were a local function call.
How it works conceptually
- Client calls a function like
result := Add(1, 2), butAddis not really local, it’s on a server. - Stub/Proxy code converts this call into a message (marshaling arguments).
- The message is sent over the network (often TCP/HTTP).
- The Server receives the message, unpacks the arguments, calls its own local
Addfunction. - The result is sent back over the network.
- The Client stub unpacks the result and returns it, so the client code thinks it just called a local function.
Usage
A server registers an object, making it visible as a service with the name of the type of the object.
// rpc server
package server
import "errors"
type Args struct {
A, B int
}
type Quotient struct {
Quo, Rem int
}
// This is service object.
// It's special method will be accessed by remote client.
type Arith int
// Remote method.
func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
// Remote method.
func (t *Arith) Divide(args *Args, quo *Quotient) error {
if args.B == 0 {
return errors.New("divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
return nil
}
void main() int {
arith := new(Arith)
// regishter arith as service object.
rpc.Register(arith)
rpc.HandleHTTP()
l, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("listen error:", err)
}
go http.Serve(l, nil)
}
Only methods that satisfy like this will be made available for remote access,
func (t *T) MethodName(argType T1, replyType *T2) error
At this point, clients can see a service Arith with methods Arith.Multiply and Arith.Divide. To invoke one, a client first dials the server:
client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
if err != nil {
log.Fatal("dialing:", err)
}
// Synchronous call
args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done // will be equal to divCall
// check errors, print, etc.
Goroutines
select
select lets a goroutine wait on multiple communication operations (channel send/receive).
It’s like a switch, but for channels:
- It picks one case whose channel is ready.
- If multiple cases are ready → it chooses one at random.
- If none are ready → it blocks (unless you have a
defaultcase).
For example:
select {
case e.ch <- req:
// the request has been sent (send succeeded)
case <-e.done:
// entire Network has been destroyed (done channel closed or received a signal)
return false
}
This means:
- Try to send
reqinto channele.ch. - If that’s not possible immediately (e.g., channel is full / no receiver), then it also checks if
<-e.doneis ready (maybe the network was shut down). - If
e.doneis closed or has a value, it will take that branch instead of blocking forever.
Test
In Go, testing is built into the standard library using the testing package. The go test command automatically runs your tests.
go test is a command-line tool for running automated tests in Go. It:
- Looks for files ending in
_test.go. - Runs functions inside those files that start with
Test,Benchmark, orExample. - Reports whether tests pass or fail.
A test function has this signature:
func TestXxx(t *testing.T) {
// test logic here
}
- Must be in a file ending with
_test.go. - The name must start with
Test. - Takes a single parameter:
*testing.T.
Options
go test -v→ verbose, shows each test name.go test ./...→ run tests in all subdirectories.go test -run=Name→ run only matching test(s).
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
want := 5
if got != want {
t.Errorf("Add(2, 3) = %d; want %d", got, want)
}
}
go test -v -run=Add
Comments
No approved comments yet.
Your display name and plain-text comment become public only after owner approval. No account or email is required.