首頁 > 後端開發 > Golang > 主體

函數中輸入參數的可變類型

WBOY
發布: 2024-02-09 20:54:10
轉載
661 人瀏覽過

函數中輸入參數的可變類型

php小編蘋果為您介紹函數中輸入參數的可變型別。在php中,函數的參數型別可以是固定的,也可以是可變的。可變類型參數,指的是函數可以接受不同類型的參數作為輸入,這在處理不同場景下的資料非常有用。透過使用特殊的參數標識符,例如“...”,我們可以在函數定義中聲明可變類型參數。這使得我們能夠更靈活地處理各種不同類型的數據,提高程式碼的複用性和可讀性。無論是字串、數字、陣列或是其他類型,我們都可以輕鬆地將它們作為參數傳遞給函數,並在函數內部進行相應的處理。這種靈活的參數類型處理方式,讓我們的程式碼更加健壯和適應性強,能夠應付各種複雜的業務需求。

問題內容

我建立了一個函數來取得使用者對拉取請求的最後評論。我正在使用“github.com/google/go-github/github”包。我想將它用於 []*github.issuecomment 和 []*github.pullrequestcomment 類型。有沒有辦法使輸入參數的類型可變,這樣我就不必在函數定義中指定它,並且可以使用任一類型呼叫函數?

func getlastuserinteractionpr(comments_array *github.issuecomment or *github.pullrequestcomment)(*github.issuecomment or *github.pullrequestcomment) {
}
登入後複製

泛型的使用:

func getlastuserinteractionpr(comments_array any)(any) {
}
登入後複製

這是一個緊急解決方案,因為我正在做的整個專案都是用 go 1.14 編寫的,而這個功能可以從 go 1.18 中獲得

當我嘗試使用空介面{}作為輸入類型時:

#
func getLastUserInteractionPRIssue(comments_array interface{})(*github.IssueComment) {

comments_array []*github.IssueComment(comments_array); err {
fmt.Println("success")
    } else {
        fmt.Println("failure")
    }
}
登入後複製

解決方法

你關心例如的內部結構嗎? issuecomment

type issuecomment struct {
    id        *int64     `json:"id,omitempty"`
    nodeid    *string    `json:"node_id,omitempty"`
    body      *string    `json:"body,omitempty"`
    user      *user      `json:"user,omitempty"`
    reactions *reactions `json:"reactions,omitempty"`
    createdat *time.time `json:"created_at,omitempty"`
    updatedat *time.time `json:"updated_at,omitempty"`
    // authorassociation is the comment author's relationship to the issue's repository.
    // possible values are "collaborator", "contributor", "first_timer", "first_time_contributor", "member", "owner", or "none".
    authorassociation *string `json:"author_association,omitempty"`
    url               *string `json:"url,omitempty"`
    htmlurl           *string `json:"html_url,omitempty"`
    issueurl          *string `json:"issue_url,omitempty"`
}
登入後複製

例如,您關心從中提取某些特定欄位嗎? pullrequestcomment 是一個更大的結構(它有更多欄位),您關心從中提取一些欄位嗎?

或您只想要每個的字串表示形式?您要做什麼很大程度上取決於您想如何處理傳遞的值。

如果您只想要每個string 表示,您可以使用極端(老實說,不是很安全- 我不推薦這個)範例,讓您的函數接受fmt.stringer 物件的切片:

func dostuffwithstringifiedcomments(cs []fmt.stringer) {
  // both issuecomment and pullrequestcomment provide string()
  // methods and therefore implement fmt.stringer
  for _, comment := range cs {
    dosomethingwith(comment.string())
  }
}
登入後複製

您的切片現在可以包含任一類型的對象,並且不會發生任何爆炸。缺點:它還可能包含數以億計的其他類型,但沒有一個是您想要的。因此,您需要新增類型斷言檢查:

switch t := comment.(type) {
  case github.issuecomment:
    // do good stuff
  case github.pullrequestcomment:
    // do other good stuff
  default:
    // yell and scream about the value of t
}
登入後複製

如果您想要提取某些字段,則必須組合一個採用[]interface{} 之類的函數(使其成為空介面的一部分,而不是空介面代表切片),迭代它並對切片的每個元素進行類型檢查,並提取任何有意義的字段,只要該元素屬於您期望的類型即可:

func DoStuff(comments []interface{}) error {
  for _, c : = range comments {
    if ic, ok := c.(*github.IssueComment); ok { // Remove the deref if your slice contains values, not references
      // Pull out fields and do IssueComment-specific things
      ProcessIssueComment(ic)
    } else if prc, ok := c.(*github.PullRequestComment); ok {
      // Do PRComment-specific things
      ProcessPullRequestComment(prc)
    } else {
      return(fmt.Errorf("I did not want something of type %s", t))
    }
  }
  return nil
}
登入後複製

另外:遊說專案擁有者(如果不是您)遷移到目前版本的 go。 1.14 到 2020 年才發布,但這對於 go 版本來說已經是永恆的了。

以上是函數中輸入參數的可變類型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!