Go
lastmod 2026-04-08created 2015-05-05106 edits
|
Go is a programming language developed by Google. It is a compiled language with garbage collection and good support for concurrency.
The initial design of Go began on September 21, 2007, when Robert Griesemer, Rob Pike, and Ken Thompson were working on the Inferno distributed operating system. It started as a 20% part-time project while sketching a new language on a whiteboard; in January 2008 Ken Thompson began building a compiler that generated C code, and in mid-2008 it was promoted to a full-time project. In May 2008 Ian Taylor began building a GCC front end using a draft of the Go spec, and when Russ Cox joined in late 2008, work began on turning the prototype into a practical language and libraries. It was officially announced on November 10, 2009, targeting the Linux and Mac OS X platforms. When Go first launched, it was not quite ready for building production software, but in May 2010 Rob Pike publicly announced that parts of it were actually in use at Google.
Categories
- Effective Go
- Go:Warnings - How to get rid of bad smells in your code
- Go:Receiver
- Go:Embedding
- Go:Interface
- Go:Generics
- Go:Modernize
- Go:StructTags
- Go:Fix (go fix)
- Go:encoding/json
- cgo
Modules
- Should you commit go.mod and go.sum too? - John Grib, the machine human -> The conclusion is "Yes".
Environment
- GOROOT
- Points to the directory where Go is installed (on Windows,
C:\Goby default); Go executables are in theGOROOT/binfolder and Go standard packages are in theGOROOT/pkgfolder. (When installing Go on Windows, it is set automatically as a system environment variable.)
- GOPATH
- Go looks for 3rd-party packages and user-defined packages other than the standard packages in this
GOPATH. If multiple paths are specified, 3rd-party packages are installed in the first path.
Libraries
- TinyGo - A Go Compiler For Small Places
WebRTC
Web Frameworks
Several web frameworks that make web programming in Go easier are currently under development. For a simple web server, the net/http package is enough, but for a web server that requires complex and varied features, it is better to use a web framework with many features built in.
Web frameworks generally provide features frequently required in practice, such as routing that maps requests to handlers, data binding that connects request parameters to handler parameters, context that maintains request state, and middleware that provides common functionality often used across handlers.
The following are Go web frameworks currently in use or under development. Since each framework offers different features, check in advance whether the features you need are already implemented or planned.
- Revel: https://revel.github.io
- Beego: http://beego.me
- Martini: https://github.com/go-martini/martini
- Gin: https://gin-gonic.github.io/gin
- GoCraft: https://github.com/gocraft/web
- Traffic: https://github.com/pilu/traffic
- Gorilla: http://www.gorillatoolkit.org
- Echo Web Framework
- Copper - Web app toolkit for Go
- PocketBase - Open-source backend in a single file
- Goravel - Go framework inspired by Laravel
- Pennybase - Ultra-lightweight file-based open-source BaaS
GUI
TUI/Terminal/Console
- GOCUI (gocui) - Go Console User Interface
- Huh - Go library for building interactive forms/prompts in the terminal
- Cobra - Powerful Go-based library for building CLI apps
- Fang - CLI starter kit
- Whosthere - Modern TUI-based LAN discovery tool written in Go
Git
- lazygit - simple terminal UI for git commands
Web Debugging
- GoVisual - Real-time HTTP request visualization and debugging tool for Go
Testing
Debugging
- Delve is a debugger for the Go programming language.
Linting
Logging
- zap - Blazing fast, structured, leveled logging in Go.
- lumberjack - lumberjack is a log rolling package for Go
Monitoring
Performance
- pprof++ - A Go Profiler with Hardware Performance Monitoring
Desktop
- Wails - Framework for developing desktop applications
Machine Learning
Compiler
- gARM - High-performance Go compiler specialized for ARM64
ETC
Hello, World!
Create a main.go file as follows.
Compile and run it as follows.
Or you can run it directly as follows.
Basic
Summarized with comments.
package main // 패키지명을 적는다.
func main() { // 함수명을 적는다.
var a int = 11 // 변수 문법: var [변수명] [타입] [ = 초기값]
const b int = 11 // 상수 문법: const [상수명] [타입] [ = 값]
println("a value:", a) // stdout 출력.
println("b value:", b) // stdout 출력.
var c = "haha" // 이런식으로 타입 추론이 가능하다. (상수도 가능)
println("c value:", c)
var d, e int = 33, 44 // 연달아 적는 것도 가능하다.
var f, g = 55, "Six" // 연달아 적을 때 추론이 가능하며, 다른 타입을 적는 것도 가능하다.
println("d, e value:", d, e)
println("f, g value:", f, g)
// 아래와 같이 상수를 열거할 수도 있다.
const (
Visa = "Visa"
Master = "MasterCard"
Amex = "American Express"
)
const (
Apple = iota // 0
Grape // 1
Orange // 2
)
}
%v output
If you want to override the %v format for a particular struct type, implement the String() method.
Debugging
- Debugging Go Code with GDB
- Debugging Go Code with LLDB
- Debug Golang applications: LLDB
- Debugging With Vim Go - vim/go/vim-go Debugging
Coding Guideline
Function
When it spans multiple lines, put one per line.
func NewBypassClient(
address string,
modbusHost string,
modbusPort int,
modbusInterval float64,
) (*EdgeDataProxy, error) {
// ...
}
Naming Convention
In Go, a name is simply declared Public if it starts with an uppercase letter, and Private if it starts with a lowercase letter.
Constant Variable
Go uses the following conventions for naming constants:
Regular constants
Use CamelCase (uppercase first letter for public, lowercase for private)
Enumerated constants (iota)
CamelCase or PascalCase
Global or package-level constants
PascalCase (starting with an uppercase letter)
Key features
- SCREAMING_SNAKE_CASE is not used (unlike C/C++)
- Uppercase first letter = public (accessible from other packages)
- Lowercase first letter = private (accessible only within the same package)
- Acronyms are all uppercase (HTTP, URL, JSON, etc.)
Optimization
Address-of rules for temporary values
The Go language spec defines "a function's return value as a value whose address cannot be taken (non-addressable value)".
// ❌ 컴파일 에러: cannot take the address of random.GenerateRandomProgramName()
name := &random.GenerateRandomProgramName()
A function's return value lives in a temporary memory location, and since the compiler may store it in a register or handle it in other ways during optimization, its address cannot be referenced directly.
func stringPtr(s string) *string {
// 1. 함수 호출 시: random.GenerateRandomProgramName()의 반환값이
// 매개변수 s로 복사됨 (call by value)
// 2. s는 함수의 지역 변수로 메모리에 할당됨
// 3. 컴파일러의 escape analysis가 &s를 감지
// 4. s를 힙에 할당 (스택 대신)
return &s // 5. 힙 주소를 반환 (함수 종료 후에도 유효)
}
// ✅ 가능
name := stringPtr(random.GenerateRandomProgramName())
Why this case works:
- Function parameters are addressable
- s is allocated in memory as a local variable of the function
- It has a definite memory address, so &s is possible
- The Go compiler detects that &s is returned outside the function
- It allocates s on the heap rather than the stack, ensuring it remains valid after the function returns
- Safe because the garbage collector manages it
Generalized with generics (Go 1.18+):
rune
In Go, rune is an alias for int32 and represents a single Unicode character:
Comparing file paths
How to check in Go whether two file paths are exactly the same:
Using the Go:filepath package
Possible with a combination of filepath.EvalSymlinks + filepath.Clean:
package main
import (
"fmt"
"os"
"path/filepath"
)
// SamePath checks if two paths point to the same location
// 두 경로가 동일한 위치를 가리키는지 확인
func SamePath(path1, path2 string) (bool, error) {
// Resolve symlinks and get absolute paths
// 심볼릭 링크를 해석하고 절대 경로를 얻음
abs1, err := filepath.EvalSymlinks(path1)
if err != nil {
return false, err
}
abs2, err := filepath.EvalSymlinks(path2)
if err != nil {
return false, err
}
// Clean the paths to remove redundant elements
// 경로를 정규화하여 중복 요소 제거
clean1 := filepath.Clean(abs1)
clean2 := filepath.Clean(abs2)
return clean1 == clean2, nil
}
func main() {
path1 := "."
path2 := "./test/.."
same, err := SamePath(path1, path2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("'%s' and '%s' are same: %v\n", path1, path2, same)
}
Using Go:os#SameFile
Using os.SameFile (recommended)
package main
import (
"fmt"
"os"
)
// SameFileCheck checks if two paths refer to the same file
// 두 경로가 동일한 파일을 참조하는지 확인 (inode 비교)
func SameFileCheck(path1, path2 string) (bool, error) {
// Get file info for both paths
// 두 경로의 파일 정보를 가져옴
info1, err := os.Stat(path1)
if err != nil {
return false, err
}
info2, err := os.Stat(path2)
if err != nil {
return false, err
}
// Compare using os.SameFile (compares inode on Unix, file index on Windows)
// os.SameFile로 비교 (Unix는 inode, Windows는 file index 사용)
return os.SameFile(info1, info2), nil
}
func main() {
path1 := "."
path2 := "./test/.."
same, err := SameFileCheck(path1, path2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("'%s' and '%s' are same: %v\n", path1, path2, same)
}
Scripting in Go instead of Python
Introduces a trick for running a Go file directly like an executable:
- Put
//usr/local/go/bin/go run "$0" "$@"; exiton the first line and give it execute permission, and it can be run as./script.go - This is not a shebang; it relies on the POSIX behavior where the shell falls back to
/bin/shwhen ENOEXEC occurs - The shell runs the first line as a command, while the Go compiler treats it as a
//comment and ignores it - Passes its own path with "$0" so go run builds and runs the script, and passes arguments with $@
- Go's powerful standard library and backward compatibility guarantee make it well suited for scripting; as long as you use Go 1.x, a script can keep working for decades
- Avoids the complexity of Python virtual environments and dependency management with pip/poetry/uv, etc.
- A shebang (#!) specifies an interpreter through the execve system call, but the technique introduced in this post is not a shebang
See also
- Layered Design - Design method for preventing circular package references.
Troubleshooting
Undefined: sort.Slice
# github.com/go-delve/delve/pkg/proc
.golang/src/github.com/go-delve/delve/pkg/proc/fncall.go:338: undefined: sort.Slice
Update to the latest version. (Solved on January 21, 2019 by updating to version 1.11.4.)
Favorite site
- The Go Programming Language
- Wikipedia (en) description of GO
- [Recommended] Python vs Go comparison reference (Comparison reference for Python and Go ~ versions Python 3.5+ and Go 1.7+ respectively ~)
Tutorials
- A Tour of Go
- [Recommended] Learning GO programming by example
- Getting started with the Go language
- An Introduction to Programming in Go - Explained simply.
Guide
- [Recommended] Notes on structured concurrency, or: Go statement considered harmful
- Vim configuration for go (vim-go)
- Debugging Go applications inside containers
- Golang package names (Package Names)
- [Original] Writing secure Go code | Jakub Jarosz
Article
- A story about benchmarking Golang vs Rust performance (Go, Rust)
- How to choose between "Rust" and "Go" (Go, Rust)
- Go vs Bun: is Go really faster than a JS runtime? | GeekNews (go, bun)
- [Original] TSBOARD | Type Safety Community Builder
- A post in which the author, after using Go for years and then switching to Java, explains the limitations and problems of Go they experienced
- Presents the view that Go's character as a simple and boring language can be a drawback rather than an advantage
- Go's philosophy: Google's Go design team emphasized simplicity and restriction, but this leads to repetitive work that users must handle themselves
- ACDSee
- Blog comment hosting service
- Bubble Tea
- Bun
- C++
- Cgo
- Cobra
- Command-line interface
- Computer Language
- Containerd
- Curriculum
- Darktable
- Delve
- DigiKam
- Documentation generator
- Echo Web Framework
- Elder
- Eleventy
- Email-go
- Fang
- FrankenPHP
- Fusion.ssg
- Fyne
- GARM
- GatsbyJS
- Geeqie
- Gitmal
- GNOME Photos
- Go support for Protocol Buffers
- Go:context
- Go:Embedding
- Go:encoding/json
- Go:Fix
- Go:Generics
- Go:Interface
- Go:math/rand
- Go:Modernize
- Go:Receiver
- Go:reflect
- Go:StructTags
- Go:sync
- Go:testing
- Go:text/template
- Go:Warnings
- Gocopper
- Gofmt
- Gokapi
- Gokey
- GoLand
- GoMLX
- Goravel
- GoScript
- GoVisual
- GRPC:Go
- GThumb
- Gwenview
- Hermes
- Hexo
- Hugo
- Huh
and 50 more