なぜGo言語がエンジニアに人気なのか?
Go(Golang)は、Google社が開発したオープンソースのプログラミング言語です。シンプルな構文・高速なコンパイル・並行処理の容易さにより、バックエンド開発・CLI・クラウドネイティブ開発で急速に普及しています。2024〜2026年のJetBrains調査では、毎年利用者が増加し続けており、エンジニアの給与水準も高い人気言語です。
Go言語の主な特徴
- シンプルな構文:キーワードが25個と少なく、覚えやすい
- 高速コンパイル:大規模プロジェクトでも数秒でビルド完了
- ゴルーチン:軽量スレッドで並行処理を簡単に実装
- 静的型付け:コンパイル時にエラーを検出
- 標準ライブラリが充実:外部依存を最小限にできる
- クロスコンパイル:Windows/Mac/Linux向けのバイナリを1コマンドで生成
Go言語入門:基本構文から始める
Hello Worldとパッケージの基礎
// main.go
package main // すべてのGoプログラムはpackage mainから始まる
import (
"fmt"
"time"
"strings"
)
func main() {
fmt.Println("こんにちは、Go言語!")
// 変数宣言の方法(3種類)
var name string = "Tech Athletes" // 明示的な型宣言
age := 5 // 型推論(短縮記法)
var ( // 複数変数をまとめて宣言
language = "Go"
version = "1.23"
)
fmt.Printf("%s はバージョン %s, %d歳です\n", name, version, age)
fmt.Println("言語:", language)
fmt.Println("現在時刻:", time.Now().Format("2006年01月02日 15:04:05"))
fmt.Println(strings.ToUpper("go is awesome"))
}
構造体(struct)とメソッド
package main
import "fmt"
// 構造体の定義(Goにはclassがない)
type Engineer struct {
Name string
Skills []string
YearsExp int
IsRemote bool
}
// メソッドの定義(レシーバーを使う)
func (e Engineer) Introduce() string {
return fmt.Sprintf(
"私は%sです。%d年の経験があります。スキル: %v",
e.Name, e.YearsExp, e.Skills,
)
}
func (e Engineer) AnnualSalary() int {
base := 4000000 // 400万円
return base + (e.YearsExp * 500000) // 経験1年ごとに50万円増
}
// インターフェースの定義
type Introducer interface {
Introduce() string
}
func PrintIntroduction(i Introducer) {
fmt.Println(i.Introduce())
}
func main() {
kasata := Engineer{
Name: "kasata",
Skills: []string{"Go", "Python", "TypeScript", "AWS"},
YearsExp: 7,
IsRemote: true,
}
PrintIntroduction(kasata)
fmt.Printf("想定年収: %d円\n", kasata.AnnualSalary())
}
Go言語の最大の特徴:ゴルーチンによる並行処理
Goのゴルーチン(goroutine)は、数KB程度の軽量スレッドで、数万〜数百万のゴルーチンを同時に実行できます。
package main
import (
"fmt"
"sync"
"time"
)
// チャネルを使った並行処理
func fetchURL(url string, results chan<- string, wg *sync.WaitGroup) {
defer wg.Done()
// 実際はHTTPリクエストをここで行う
time.Sleep(100 * time.Millisecond) // シミュレート
results <- fmt.Sprintf("%s: 200 OK (100ms)", url)
}
func main() {
urls := []string{
"https://api.example.com/posts",
"https://api.example.com/users",
"https://api.example.com/comments",
}
results := make(chan string, len(urls))
var wg sync.WaitGroup
start := time.Now()
// 全URLを並行取得(逐次処理より約3倍速い)
for _, url := range urls {
wg.Add(1)
go fetchURL(url, results, &wg)
}
// 全ゴルーチンの完了を待つ
go func() {
wg.Wait()
close(results)
}()
// 結果を収集
for result := range results {
fmt.Println(result)
}
fmt.Printf("合計時間: %v (逐次処理なら約300ms)\n", time.Since(start))
}
// 出力例: 合計時間: 101ms
Go言語でWebサーバーを作る(標準ライブラリのみ)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
)
type Article struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Author string `json:"author"`
}
var articles = []Article{
{1, "Go言語入門", "Goで始めるプログラミング", "kasata"},
{2, "FastAPI入門", "Python WebAPI開発", "kasata"},
}
func articlesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
json.NewEncoder(w).Encode(articles)
case http.MethodPost:
var newArticle Article
if err := json.NewDecoder(r.Body).Decode(&newArticle); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
newArticle.ID = len(articles) + 1
articles = append(articles, newArticle)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newArticle)
}
}
func articleByIDHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
idStr := r.URL.Path[len("/articles/"):]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "無効なIDです", http.StatusBadRequest)
return
}
for _, a := range articles {
if a.ID == id {
json.NewEncoder(w).Encode(a)
return
}
}
http.Error(w, "記事が見つかりません", http.StatusNotFound)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/articles", articlesHandler)
mux.HandleFunc("/articles/", articleByIDHandler)
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"status": "ok"}`)
})
fmt.Println("サーバー起動: http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
Ginフレームワークで実用的なWebAPIを作る
go get github.com/gin-gonic/gin
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type CreateArticleInput struct {
Title string `json:"title" binding:"required,min=1,max=200"`
Content string `json:"content" binding:"required"`
Author string `json:"author" binding:"required"`
}
func main() {
r := gin.Default()
// ミドルウェア(CORS設定)
r.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Next()
})
// ルーティング
api := r.Group("/api/v1")
{
api.GET("/articles", getArticles)
api.POST("/articles", createArticle)
api.GET("/articles/:id", getArticleByID)
}
r.Run(":8080") // デフォルト; 0.0.0.0:8080
}
func getArticles(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"articles": articles,
"total": len(articles),
})
}
func createArticle(c *gin.Context) {
var input CreateArticleInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
article := Article{
ID: len(articles) + 1,
Title: input.Title,
Content: input.Content,
Author: input.Author,
}
articles = append(articles, article)
c.JSON(http.StatusCreated, article)
}
まとめ:Go言語の学習ロードマップ
- 基本構文(2週間):変数、関数、構造体、インターフェース
- 並行処理(1週間):ゴルーチン、チャネル、sync.WaitGroup
- 標準ライブラリ(1週間):net/http、encoding/json、os
- WebフレームワークとDB(2週間):Gin + GORM
- テストとベンチマーク(1週間):testing パッケージ
- 実際のプロジェクト:CLI、API、マイクロサービスの実装
GoはDockerやKubernetes・Terraformのような有名OSSで採用されている言語です。クラウドネイティブ開発・マイクロサービス・高パフォーマンスAPIを目指すエンジニアに強くおすすめします。