Generics Basics
Generic Identity
A generic identity function keeps one operation shape while the caller chooses the value type.
Generic Identity
generic_identity.go
package main
import "fmt"
// Generic shape: Identity[T any](value T) T
func IdentityString(value string) string {
return value
}
func main() {
var word =
result := IdentityString(word)
length := len(result)
fmt.Println("word=", word)
fmt.Println("result=", result)
fmt.Println("length=", length)
}
package main
import "fmt"
// Generic shape: Identity[T any](value T) T
func IdentityString(value string) string {
return value
}
func main() {
var word =
result := IdentityString(word)
length := len(result)
fmt.Println("word=", word)
fmt.Println("result=", result)
fmt.Println("length=", length)
}
package main
import "fmt"
// Generic shape: Identity[T any](value T) T
func IdentityString(value string) string {
return value
}
func main() {
var word =
result := IdentityString(word)
length := len(result)
fmt.Println("word=", word)
fmt.Println("result=", result)
fmt.Println("length=", length)
}
type parameter
A type parameter lets one function work with more than one concrete type. The trace uses a concrete string helper and shows the generic shape in a comment.