Skip to content

Instantly share code, notes, and snippets.

@jqjk
Last active June 20, 2022 06:40
Show Gist options
  • Save jqjk/b6cb7ef94c4a6547b3376268e8bcb877 to your computer and use it in GitHub Desktop.
Save jqjk/b6cb7ef94c4a6547b3376268e8bcb877 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type Int int
func (n Int) Equal(m Int) bool { return n == m }
type Comparable[T any] interface {
Equal(T) bool
}
func Contains[T Comparable[T]](haystack []T, needle T) bool {
for _, hay := range haystack {
if hay.Equal(needle) {
return true
}
}
return false
}
func main() {
// 【TRY】含まれているか調べる
fmt.Println(Contains([]Int{10, 20, 30}, 10)) // true
}
@jqjk
Copy link
Author

jqjk commented Jun 13, 2022

@jqjk
Copy link
Author

jqjk commented Jun 20, 2022

package main

import (
	"fmt"
)

type Int int

func Contains[T comparable](haystack []T, needle T) bool {
	for _, hay := range haystack {
		if hay == needle {
			return true
		}
	}
	return false
}

func main() {
	// 【TRY】含まれているか調べる
	fmt.Println(Contains([]Int{10, 20, 30}, 10)) // true
}

https://docs.google.com/presentation/d/1TqCv_ECXBVGw1XOQ-v6rVRyiYGczl4yhDCJIhNLpzaQ/edit#slide=id.gd0cc1c3878_0_146
組み込み comparable 使用バージョン

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment