搜索
首页后端开发Golang函数中输入参数的可变类型

函数中输入参数的可变类型

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 对象的切片: p>

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。如有侵权,请联系admin@php.cn删除
掌握GO弦:深入研究'字符串”包装掌握GO弦:深入研究'字符串”包装May 12, 2025 am 12:05 AM

你应该关心Go语言中的"strings"包,因为它提供了处理文本数据的工具,从基本的字符串拼接到高级的正则表达式匹配。1)"strings"包提供了高效的字符串操作,如Join函数用于拼接字符串,避免性能问题。2)它包含高级功能,如ContainsAny函数,用于检查字符串是否包含特定字符集。3)Replace函数用于替换字符串中的子串,需注意替换顺序和大小写敏感性。4)Split函数可以根据分隔符拆分字符串,常用于正则表达式处理。5)使用时需考虑性能,如

GO中的'编码/二进制”软件包:您的二进制操作首选GO中的'编码/二进制”软件包:您的二进制操作首选May 12, 2025 am 12:03 AM

“编码/二进制”软件包interingoisentialForHandlingBinaryData,oferingToolSforreDingingAndWritingBinaryDataEfficely.1)Itsupportsbothlittle-endianandBig-endianBig-endianbyteorders,CompialforOss-System-System-System-compatibility.2)

Go Byte Slice操纵教程:掌握'字节”软件包Go Byte Slice操纵教程:掌握'字节”软件包May 12, 2025 am 12:02 AM

掌握Go语言中的bytes包有助于提高代码的效率和优雅性。1)bytes包对于解析二进制数据、处理网络协议和内存管理至关重要。2)使用bytes.Buffer可以逐步构建字节切片。3)bytes包提供了搜索、替换和分割字节切片的功能。4)bytes.Reader类型适用于从字节切片读取数据,特别是在I/O操作中。5)bytes包与Go的垃圾回收器协同工作,提高了大数据处理的效率。

您如何使用'字符串”软件包在GO中操纵字符串?您如何使用'字符串”软件包在GO中操纵字符串?May 12, 2025 am 12:01 AM

你可以使用Go语言中的"strings"包来操纵字符串。1)使用strings.TrimSpace去除字符串两端的空白字符。2)用strings.Split将字符串按指定分隔符拆分成切片。3)通过strings.Join将字符串切片合并成一个字符串。4)用strings.Contains检查字符串是否包含特定子串。5)利用strings.ReplaceAll进行全局替换。注意使用时要考虑性能和潜在的陷阱。

如何使用'字节”软件包在GO中操纵字节切片(逐步)如何使用'字节”软件包在GO中操纵字节切片(逐步)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

Go Bytes软件包:有什么选择?Go Bytes软件包:有什么选择?May 11, 2025 am 12:11 AM

thealternativestogo'sbytespackageincageincludethestringspackage,bufiopackage和customstructs.1)thestringspackagecanbeusedforbytemanipulationforbytemanipulationbybyconvertingbytestostostostostostrings.2))

操纵字节切片在GO:'字节”软件包的功能操纵字节切片在GO:'字节”软件包的功能May 11, 2025 am 12:09 AM

“字节”包装封装forefforeflyManipulatingByteslices,CocialforbinaryData,网络交易和andfilei/o.itoffersfunctionslikeIndexForsearching,BufferForhandLinglaRgedLargedLargedAtaTasets,ReaderForsimulatingStreamReadReadImreAmreadReamReadinging,以及Joineffiter和Joineffiter和Joineffore

Go Strings套餐:弦乐操纵的综合指南Go Strings套餐:弦乐操纵的综合指南May 11, 2025 am 12:08 AM

go'sstringspackageIscialforficientficientsTringManipulation,uperingToolSlikestrings.split(),strings.join(),strings.replaceall(),andStrings.contains.contains.contains.contains.contains.contains.split.split(split()strings.split()dividesStringoSubSubStrings; 2)strings.joins.joins.joinsillise.joinsinelline joinsiline joinsinelline; 3);

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!