Welcome to Tech Athletes | テック・アスリート   Click to listen highlighted text! Welcome to Tech Athletes | テック・アスリート

Go言語(Golang)入門完全ガイド【2026年版】|インストール・基礎文法・goroutine・API開発まで

Goとは?2026年のシステム開発に欠かせない理由

Go(Golang)はGoogleが開発したオープンソースのプログラミング言語です。シンプルな文法・高速な実行速度・並行処理の強さから、クラウドサービス・マイクロサービス・CLIツール開発で急速に普及しています。DockerやKubernetes自体もGoで書かれています。

Goの主な特徴

  • 静的型付け:コンパイル時にエラーを検出
  • 高速コンパイル:Cレベルの実行速度
  • goroutine:軽量な並行処理を簡単に記述
  • シンプルな文法:習得が容易で読みやすい
  • 標準ライブラリが充実:HTTPサーバー・暗号化・JSON処理が標準で使える

インストールと環境構築

# Macの場合
brew install go
go version  # go version go1.22.x darwin/amd64

# Windowsの場合
# https://go.dev/dl/ からインストーラーをダウンロード

# プロジェクト作成
mkdir my-go-app && cd my-go-app
go mod init github.com/yourusername/my-go-app

# VSCode拡張機能のインストール
code --install-extension golang.go

Hello World から始める基礎文法

package main

import (
    "fmt"
    "strings"
    "strconv"
)

func main() {
    fmt.Println("Hello, Tech Athletes!")
    
    // 変数宣言
    var name string = "Golang"
    version := 1.22  // 型推論
    year := 2026
    isAwesome := true
    
    fmt.Printf("%s %.2f (%d) - Awesome: %v
", name, version, year, isAwesome)
    
    // 文字列操作
    message := "エンジニアのための技術ブログ"
    fmt.Println(strings.ToUpper("tech athletes"))
    fmt.Println(len(message))
    
    // 配列とスライス
    langs := []string{"Go", "Python", "Rust", "TypeScript"}
    langs = append(langs, "Zig")
    
    for i, lang := range langs {
        fmt.Printf("%d: %s
", i+1, lang)
    }
    
    // マップ
    salaries := map[string]int{
        "Junior": 500,
        "Mid":    700,
        "Senior": 1000,
        "Staff":  1500,
    }
    
    for role, salary := range salaries {
        fmt.Printf("%s: %s万円
", role, strconv.Itoa(salary))
    }
}

関数・エラーハンドリング

package main

import (
    "errors"
    "fmt"
    "math"
)

// 複数戻り値(Goの特徴)
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("0で割ることはできません")
    }
    return a / b, nil
}

// 可変長引数
func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

// 無名関数とクロージャ
func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

// インターフェース
type Shape interface {
    Area() float64
    Perimeter() float64
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

func (c Circle) Perimeter() float64 {
    return 2 * math.Pi * c.Radius
}

func printShape(s Shape) {
    fmt.Printf("面積: %.2f, 周囲: %.2f
", s.Area(), s.Perimeter())
}

func main() {
    result, err := divide(10, 3)
    if err != nil {
        fmt.Println("エラー:", err)
        return
    }
    fmt.Printf("10 / 3 = %.4f
", result)
    
    fmt.Println("合計:", sum(1, 2, 3, 4, 5))
    
    counter := makeCounter()
    fmt.Println(counter(), counter(), counter()) // 1 2 3
    
    c := Circle{Radius: 5}
    printShape(c)
}

goroutineとchannelによる並行処理

package main

import (
    "fmt"
    "sync"
    "time"
)

// goroutineの基本
func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Printf("Worker %d 開始
", id)
    time.Sleep(time.Second)
    fmt.Printf("Worker %d 完了
", id)
}

// channelによるデータ通信
func producer(ch chan<- int) {
    for i := 0; i < 5; i++ {
        ch <- i
        time.Sleep(100 * time.Millisecond)
    }
    close(ch)
}

func consumer(ch <-chan int, results chan<- int) {
    for v := range ch {
        results <- v * v  // 2乗を送信
    }
    close(results)
}

// select文でタイムアウト処理
func fetchWithTimeout(timeout time.Duration) (string, error) {
    ch := make(chan string, 1)
    
    go func() {
        time.Sleep(500 * time.Millisecond) // 処理をシミュレート
        ch <- "データ取得成功"
    }()
    
    select {
    case result := <-ch:
        return result, nil
    case <-time.After(timeout):
        return "", fmt.Errorf("タイムアウト: %v", timeout)
    }
}

func main() {
    // WaitGroupで複数goroutineを管理
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }
    wg.Wait()
    
    // Channel pipeline
    nums := make(chan int, 5)
    squared := make(chan int, 5)
    
    go producer(nums)
    go consumer(nums, squared)
    
    for result := range squared {
        fmt.Printf("結果: %d
", result)
    }
}

net/httpパッケージでAPIサーバー構築

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "sync"
)

type Article struct {
    ID       int    "json:\"id\""
    Title    string "json:\"title\""
    Category string "json:\"category\""
}

var (
    articles = []Article{
        {1, "Go言語入門", "programming"},
        {2, "Kubernetes完全ガイド", "infrastructure"},
    }
    mu sync.RWMutex
)

func writeJSON(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(v)
}

func handleArticles(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        mu.RLock()
        defer mu.RUnlock()
        writeJSON(w, http.StatusOK, articles)
    case http.MethodPost:
        var a Article
        if err := json.NewDecoder(r.Body).Decode(&a); err != nil {
            writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
            return
        }
        mu.Lock()
        a.ID = len(articles) + 1
        articles = append(articles, a)
        mu.Unlock()
        writeJSON(w, http.StatusCreated, a)
    default:
        w.WriteHeader(http.StatusMethodNotAllowed)
    }
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/articles", handleArticles)
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
    })
    
    fmt.Println("サーバー起動: http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Go言語エンジニアの年収・需要

  • 未経験〜1年:500〜650万円
  • 2〜4年:700〜900万円
  • 5年以上:900〜1,400万円
  • クラウドネイティブ専門:1,200〜1,800万円

GoはDockerやKubernetesのエコシステムと親和性が高く、DevOpsエンジニア・SRE(Site Reliability Engineer)分野で特に需要が高まっています。

まとめ

Goはシンプルな文法で高いパフォーマンスを実現できる現代のシステム開発言語です。goroutineによる並行処理は他の言語にはない強みです。バックエンドAPI・マイクロサービス・CLIツール開発を目指すエンジニアに強くおすすめします。

投稿者 kasata

IT企業でエンジニアとして勤務後、テクノロジー情報メディア「Tech Athletes(テック・アスリート)」を運営。プログラミング、クラウドインフラ(AWS/GCP/Azure)、AI活用、Webサービス開発を専門とする。エンジニア・ビジネスパーソン向けに、実際に使ってみた経験をもとに信頼できる技術情報を発信中。資格:AWS認定ソリューションアーキテクト、Python 3 エンジニア認定試験合格。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

Click to listen highlighted text!