首頁 >後端開發 >Golang >如何以程式設計方式列出 Go 介面中定義的方法名稱?

如何以程式設計方式列出 Go 介面中定義的方法名稱?

Barbara Streisand
Barbara Streisand原創
2024-11-03 08:51:291043瀏覽

How do you programmatically list the method names defined in a Go interface?

在介面類型中列出方法名稱

在 Go 中,介面定義了類型必須實作的方法契約。在運行時與介面互動時,您可能需要存取其方法的名稱。

問題:

考慮以下介面定義:

type FooService interface {
    Foo1(x int) int
    Foo2(x string) string
}

如何以程式設計方式從FooService 介面產生方法名稱列表,即["Foo11 ", "Foo2"]?

答案:

要從介面類型中擷取方法名稱列表,可以使用運行時反射:

<code class="go">t := reflect.TypeOf((*FooService)(nil)).Elem()
var s []string
for i := 0; i < t.NumMethod(); i++ {
    s = append(s, t.Method(i).Name)
}</code>

說明:

  1. reflect.TypeOf( (*FooService)(nil)).Elem() 擷取介面的reflect.Type。
  2. t.NumMethod() 傳回介面中方法的數量。
  3. t.Method (i) 擷取介面的第 i 個方法。
  4. t.Method(i).Name 傳回方法的名稱。

Playground 範例:

https://go.dev/play/p/6cXnZKiKiKV1

>

請參閱「如何取得介面的reflect.Type?」有關取得介面的Reflect.Type 的見解。

以上是如何以程式設計方式列出 Go 介面中定義的方法名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn