Go 1.14下如何让函数兼容两种GitHub评论数组类型?
解决方案
在 Go 1.14 不支持泛型的前提下,你可以通过空接口配合类型断言,或者编写针对性的包装函数来实现需求,以下是具体可行方案:
方案一:空接口+类型断言(统一入口)
通过将参数定义为interface{},在函数内部对输入类型进行断言,分别处理两种评论切片,最终返回对应类型的评论(需调用方自行断言返回值):
import ( "fmt" "time" "github.com/google/go-github/github" ) func getLastUserInteractionPR(comments interface{}) (interface{}, error) { var lastComment interface{} var latestTime time.Time // 断言并处理 IssueComment 切片 if issueComments, ok := comments.([]*github.IssueComment); ok { if len(issueComments) == 0 { return nil, nil } for _, c := range issueComments { commentTime := c.CreatedAt.Time if commentTime.After(latestTime) { latestTime = commentTime lastComment = c } } return lastComment, nil } // 断言并处理 PullRequestComment 切片 if prComments, ok := comments.([]*github.PullRequestComment); ok { if len(prComments) == 0 { return nil, nil } for _, c := range prComments { commentTime := c.CreatedAt.Time if commentTime.After(latestTime) { latestTime = commentTime lastComment = c } } return lastComment, nil } // 不支持的输入类型 return nil, fmt.Errorf("unsupported comment type: %T", comments) }
调用示例
// 处理 IssueComment 切片 issueComments := []*github.IssueComment{/* 你的评论数据 */} result, err := getLastUserInteractionPR(issueComments) if err != nil { // 处理错误 } if lastIssueComment, ok := result.(*github.IssueComment); ok { // 使用 lastIssueComment } // 处理 PullRequestComment 切片 prComments := []*github.PullRequestComment{/* 你的评论数据 */} result, err := getLastUserInteractionPR(prComments) if err != nil { // 处理错误 } if lastPRComment, ok := result.(*github.PullRequestComment); ok { // 使用 lastPRComment }
方案二:编写针对性函数(更易维护)
如果不想使用类型断言,可以直接编写两个独立函数,分别处理两种评论类型,代码可读性更高,也避免了断言的复杂性:
import ( "time" "github.com/google/go-github/github" ) // 处理 IssueComment 切片 func getLastIssueComment(comments []*github.IssueComment) *github.IssueComment { if len(comments) == 0 { return nil } var lastComment *github.IssueComment var latestTime time.Time for _, c := range comments { if c.CreatedAt.Time.After(latestTime) { latestTime = c.CreatedAt.Time lastComment = c } } return lastComment } // 处理 PullRequestComment 切片 func getLastPRComment(comments []*github.PullRequestComment) *github.PullRequestComment { if len(comments) == 0 { return nil } var lastComment *github.PullRequestComment var latestTime time.Time for _, c := range comments { if c.CreatedAt.Time.After(latestTime) { latestTime = c.CreatedAt.Time lastComment = c } } return lastComment }
调用示例
// 直接调用对应函数即可 lastIssue := getLastIssueComment(issueComments) lastPR := getLastPRComment(prComments)
注意事项
你之前尝试的类型断言存在语法错误,正确的断言格式是变量, ok := 接口值.(目标类型),没有错误返回值,而是通过ok布尔值判断断言是否成功。
内容的提问来源于stack exchange,提问作者Michal Škultěty
相关产品推荐
相关产品推荐

