Skip to content
Search

Go

lastmod 2026-04-08created 2015-05-05106 edits

Go Standard Library

  • archive/tar
  • archive/zip
  • bufio
  • builtin
  • bytes
  • cmp
  • compress/bzip2
  • compress/flate
  • compress/gzip
  • compress/lzw
  • compress/zlib
  • container/heap
  • container/list
  • container/ring
  • context
  • crypto
  • crypto/aes
  • crypto/cipher
  • crypto/des
  • crypto/dsa
  • crypto/ecdh
  • crypto/ecdsa
  • crypto/ed25519
  • crypto/elliptic
  • crypto/fips140
  • crypto/hkdf
  • crypto/hmac
  • crypto/md5
  • crypto/mlkem
  • crypto/pbkdf2
  • crypto/rand
  • crypto/rc4
  • crypto/rsa
  • crypto/sha1
  • crypto/sha256
  • crypto/sha3
  • crypto/sha512
  • crypto/subtle
  • crypto/tls
  • crypto/x509
  • crypto/x509/pkix
  • database/sql
  • database/sql/driver
  • debug/buildinfo
  • debug/dwarf
  • debug/elf
  • debug/gosym
  • debug/macho
  • debug/pe
  • debug/plan9obj
  • embed
  • encoding
  • encoding/ascii85
  • encoding/asn1
  • encoding/base32
  • encoding/base64
  • encoding/binary
  • encoding/csv
  • encoding/gob
  • encoding/hex
  • encoding/json
  • encoding/json/jsontext
  • encoding/json/v2
  • encoding/pem
  • encoding/xml
  • errors
  • expvar
  • flag
  • fmt
  • go/ast
  • go/build
  • go/build/constraint
  • go/constant
  • go/doc
  • go/doc/comment
  • go/format
  • go/importer
  • go/parser
  • go/printer
  • go/scanner
  • go/token
  • go/types
  • go/version
  • hash
  • hash/adler32
  • hash/crc32
  • hash/crc64
  • hash/fnv
  • hash/maphash
  • html
  • html/template
  • image
  • image/color
  • image/color/palette
  • image/draw
  • image/gif
  • image/jpeg
  • image/png
  • index/suffixarray
  • io
  • io/fs
  • io/ioutil
  • iter
  • log
  • log/slog
  • log/syslog
  • maps
  • math
  • math/big
  • math/bits
  • math/cmplx
  • math/rand
  • math/rand/v2
  • mime
  • mime/multipart
  • mime/quotedprintable
  • net
  • net/http
  • net/http/cgi
  • net/http/cookiejar
  • net/http/fcgi
  • net/http/httptest
  • net/http/httptrace
  • net/http/httputil
  • net/http/pprof
  • net/mail
  • net/netip
  • net/rpc
  • net/rpc/jsonrpc
  • net/smtp
  • net/textproto
  • net/url
  • os
  • os/exec
  • os/signal
  • os/user
  • path
  • path/filepath
  • plugin
  • reflect
  • regexp
  • regexp/syntax
  • runtime
  • runtime/cgo
  • runtime/coverage
  • runtime/debug
  • runtime/metrics
  • runtime/pprof
  • runtime/race
  • runtime/trace
  • slices
  • sort
  • strconv
  • strings
  • structs
  • sync
  • sync/atomic
  • syscall
  • syscall/js
  • testing
  • testing/fstest
  • testing/iotest
  • testing/quick
  • testing/slogtest
  • testing/synctest
  • text/scanner
  • text/tabwriter
  • text/template
  • text/template/parse
  • time
  • time/tzdata
  • unicode
  • unicode/utf16
  • unicode/utf8
  • unique
  • unsafe
  • weak

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

Modules

Environment

GOROOT
Points to the directory where Go is installed (on Windows, C:\Go by default); Go executables are in the GOROOT/bin folder and Go standard packages are in the GOROOT/pkg folder. (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.

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.

package main
func main() {
    println("Hello, World!")
}

Compile and run it as follows.

$ go build main.go
$ ./main

Or you can run it directly as follows.

$ go run main.go

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

fmt.Printf("%v\n", req)  // 어떤 값이든 출력한다.

If you want to override the %v format for a particular struct type, implement the String() method.

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)

  const MaxRetries = 3
  const defaultTimeout = 30
Enumerated constants (iota)

CamelCase or PascalCase

  const (
      StatusPending = iota
      StatusRunning
      StatusComplete
  )
Global or package-level constants

PascalCase (starting with an uppercase letter)

  const DefaultBufferSize = 1024
  const MaxConnections = 100
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
  • Escape Analysis
    • 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+):

func Ptr[T any](v T) *T {
    return &v
}

rune

In Go, rune is an alias for int32 and represents a single Unicode character:

var r rune = '한'
fmt.Printf("%T, %v, %c\n", r, r, r)
// Output: int32, 54620, 한

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" "$@"; exit on 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/sh when 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

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

Tutorials

Guide

Article

author Zer0 sitemap