首頁  >  文章  >  後端開發  >  如何在 Go 中將陣列或切片參數傳遞給 Sprintf?

如何在 Go 中將陣列或切片參數傳遞給 Sprintf?

Patricia Arquette
Patricia Arquette原創
2024-10-27 20:30:02987瀏覽

How to Pass Array or Slice Parameters to Sprintf in Go?

將變數參數傳遞給Go 中的Sprintf

Go 中的Printf 函數允許使用指定的格式字串格式化和列印輸出,後跟可變數量的參數。但是,如果您希望傳遞陣列或值切片作為參數,則可能會遇到類型錯誤。

考慮以下範例:

<code class="go">s := []string{"a", "b", "c", "d"}  // Result from regexp.FindStringSubmatch()
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])</code>

執行此程式碼會產生錯誤:

cannot use v (type []string) as type []interface {} in argument to fmt.Printf

要解決此問題,您必須將切片宣告為[]interface{ } 類型。這是因為 Printf 需要該類型的參數。

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

另一個選項是在將 []string 傳遞給 Printf 之前手動將其轉換為 []interface{}。

<code class="go">ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}</code>

使用此方法可讓您將 is 切片作為變數參數傳遞給 Printf。

以上是如何在 Go 中將陣列或切片參數傳遞給 Sprintf?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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