Skip to content

proposal: slices: CloneAny and Contains2 #74450

Closed as not planned
Closed as not planned
@XangelMusic

Description

@XangelMusic

Proposal Details

CloneAny and Contains2 (names subject to change) are functions I needed when designing my own code but weren't available in slices. These function proposals are quite rudimentary and I believe are good patterns to have in go for everyone to use.


Firstly, CloneAny resolves an issue for me when using a slice of a certain type into a variadic function. It turned out I couldn't use a slice of Strings into this function, and how CloneAny would resolve this is by cloning a slice into another slice of type Any.

Below is the code I created for my project that will essentially be CloneAny:

urls := xurls.Strict().FindAllString(content, -1)
var anyUrls []any
for _, url := range urls {
	anyUrls = append(anyUrls, url)
}

return fmt.Sprintf(strings.Join(contents, "\n"), anyUrls...)

Basically, xurls.Strict returned a slice of Strings which I couldn't use into the variadic function fmt.Sprintf.


Secondly, Contains2 is the same as Contains only we're looking through a slice of values instead of just one. ContainFunc also couldn't facilitate my needs when I wanted to check if any of these values is present in the main slice. Its essentially a nested loop as the following code I created for my project will demonstrate:

for _, tag := range contents {
	for _, test := range aiTags {
		if strings.EqualFold(tag, test) {
			return true
		}
	}
}
return false

This code is for a Discord bot and checks whether an image from X (Twitter) is an AI Generated image. It looks through a post and checks whether one of the several aiTags is present in that post.

Note: the strings.EqualFold function in the code example isn't relevant for Contains2 but might be a possible example for a Contains2Func instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions