跳轉到

Go Interface Contract Build Enforcement

概念概覽

Go Interface 型別不符的 Build-time 阻斷特性

核心知識

Go Interface 型別不符的 Build-time 阻斷特性

Go 的 interface 契約在 go build / go test 階段就會強制驗證。若實作方法的回傳型別與 interface 定義不符,即使邏輯上「幾乎相容」(如 interface{} vs []byte),編譯器也會直接報錯,不等到 runtime。

// interface 定義(activity_handler.go:37)
GetPlayerProgress(...) ([]byte, error)

// 實作(sticker_season_handler.go:411)—— 會造成 build fail
GetPlayerProgress(...) (interface{}, error)

實務意涵

  • 跨模組整合前必須先對齊 interface 契約,不能依賴整合測試發現問題
  • 整合測試有時會跳過 build fail 的模組,導致型別不符被掩蓋
  • go test ./internal/modules/sticker/... 直接 build fail 是最明確的 blocker 訊號
  • 修復方向:讓實作的回傳型別與 interface 定義完全一致,不能用寬型別代替

經驗教訓

  • interface{} 看似最通用,但在 Go interface 契約中反而是不相容的,因為 concrete type 滿足不了 interface{} 宣告位置的類型推斷

  • go build 比整合測試更早、更確定地發現介面不相容,應優先跑 unit build 確認

  • 跨模組整合點(handler 實作某個 interface)必須在 Phase 開始前就 go build 驗證,而不是等到接線時才發現

常見陷阱

  • 用 interface{} 作為回傳型別以為可以「向上相容」,實際上在 Go 的 interface 滿足規則中並不成立

  • 只跑高層整合測試而跳過個別 module 的 go test,導致 build fail 被忽略

相關概念

來源 Sessions

日期 Session 貢獻摘要

| 2026-04-02 | 431f3410-f7d5-461d-8a0b-e1ea3f999e73 | 具體說明 Go interface return type 不符(interface{} vs []byte)如何在 build 階段直接阻斷跨模組整合,比 runtime 問題更早暴露 |


本概念頁面由 Semi-Brain Wiki 系統自動維護

最後更新: 2026-04-02