後端工坊 2026 年 5 月 28 日

2026-05-28 — C++26 Structured Bindings、Go 泛型方法接受、pkg.go.dev API

primary=https://isocpp.org/blog/2026/05/cpp26-structured-bindings-in-conditions-sandor-dargo primary=https://github.com/golang/go/issues/77273 primary=https://go.dev/blog/pkgsite-api

C++26 Structured Bindings in Conditions:條件式中的解構與判斷一次到位

isocpp.org / Sandor Dargo · 2026-05-26

C++26 引入在 ifwhilefor 條件式中直接使用 structured binding 的語法,讓開發者可在同一陳述式完成解構與條件判斷,不必宣告只使用一次的中間變數。

C++17 的限制與 C++26 的擴充

C++17 允許 structured binding 作為一般宣告(auto [a, b] = f();),但不能直接放在 if / while / for 的條件位置。C++26 補齊了這個空缺,允許 structured binding 出現在 init-statement 或條件運算式中:

// C++26 語法
if (auto [it, inserted] = map.emplace(key, val); inserted) {
    use(it);
}

binding 的作用域涵蓋 if 的兩個分支及條件式本身,與既有 init-statement 規則一致。

實用場景

  • std::map::emplace / insert 回傳 pair<iterator, bool>,可直接在 if 條件中解構並判斷成功與否
  • std::expected 的值與錯誤分支,在條件式中直接展開
  • 網路回應解構:同時取得 status code 與 body,並在同一條件判斷 HTTP 2xx
  • while 迴圈中的 coroutine / generator yield 結果反覆解構

影響範圍

此特性為純語法擴充,不影響 ABI 也不需 runtime 支援。GCC、Clang、MSVC 均已規劃在各自的 C++26 實作中加入。對既有程式碼完全向後相容。

原始來源:isocpp.org — C++26: Structured Bindings in Conditions


Go 泛型方法提案正式接受(目標 Go 1.27):method 可宣告獨立型別參數

Go GitHub Issues · 2026-05-28

Go 核心團隊已接受 Issue #77273,允許 concrete type 的 method 宣告自己的型別參數,目標版本為 Go 1.27。這是 Go 泛型(1.18 引入)以來最重要的語法擴充,填補 function 與 method 在泛型表達力上的長期不對稱。

問題根源

Go 規格將 method 定義為帶 receiver 的 function,但泛型推出時明確禁止 method 宣告型別參數。根本障礙在於 interface 實作的動態性:Go 不要求具體型別聲明其 interface 實作,編譯器無法靜態知曉泛型 method 的所有 instantiation,難以為每個 interface 匹配版本生成 vtable entry。提案透過規定「泛型 concrete method 不實作 interface method」解開這個循環。

語法規格

MethodDecl 語法在 MethodName 之後插入可選的 [TypeParameters]

// 泛型 method,T 為 method 自身的型別參數
func (s *Storage) Get[T any](key string) T { ... }

// 呼叫端:型別推斷或明確傳遞
val := store.Get[int]("count")

型別參數作用域從 method 名稱延伸至 body 結尾,與既有泛型函式規則一致。

實作工作量

  • Parser:已接受語法,移除錯誤路徑即可啟用
  • Type checker:移除對應限制,複雜度較低
  • Backend:泛型 method 呼叫可編譯期轉為 function 呼叫,與既有泛型 function 路徑共用
  • Import/export 資料格式:需更新以攜帶新 method 型別資訊,為最複雜部分
  • Reflection:泛型 method 暫不透過 reflection 存取

原始來源:Go GitHub — Issue #77273


pkg.go.dev /v1beta API 正式推出:查詢套件元資料、符號與弱點的標準化端點

Go Blog · 2026-05-21

Go 官方模組探索平台 pkg.go.dev 推出程式化 API,路徑前綴 /v1beta。API 為 stateless GET-only 設計,提供套件元資料、模組版本清單、符號宣告、反向相依性及弱點查詢。穩定後計劃升版為 /v1

核心端點

端點說明
/v1beta/package/{path}套件元資料
/v1beta/module/{path}模組元資料
/v1beta/versions/{path}模組所有已發布版本
/v1beta/symbols/{path}套件宣告的所有符號
/v1beta/imported-by/{path}引用指定套件的其他套件
/v1beta/vulns/{path}已知弱點
/v1beta/search?q={query}全文搜尋

版本指定語意

version query parameter 支援語意版本與分支名稱。傳入 ?version=main 時,API 自動解析為對應 pseudo-version(如 v0.7.1-0.20260310220054-34c9473539b8)。省略時預設取最新 tag 版本。

精確性設計

若套件路徑在多個模組中存在,API 回傳候選清單並要求呼叫者明確指定模組路徑,不自動猜測。OpenAPI 規格位於 https://pkg.go.dev/v1beta/openapi.yaml;端點 URL 保證向後相容。

curl https://pkg.go.dev/v1beta/package/github.com/google/go-cmp/cmp | jq .version

原始來源:Go Blog — Introducing the pkg.go.dev API


End of article
0
Would love your thoughts, please comment.x
()
x