Generics Basics
Generic Box
A generic struct stores a value whose type is supplied when the struct is used.
Generic Box
generic_box.go
package main
import "fmt"
// Generic shape: Box[T any] struct { Value T }
type IntBox struct {
Value int
}
func (box IntBox) String() string {
return fmt.Sprint(box.Value)
}
func main() {
var size =
box := IntBox{Value: size}
text := box.String()
fmt.Println("size=", size)
fmt.Println("text=", text)
fmt.Println("double=", box.Value*2)
}
package main
import "fmt"
// Generic shape: Box[T any] struct { Value T }
type IntBox struct {
Value int
}
func (box IntBox) String() string {
return fmt.Sprint(box.Value)
}
func main() {
var size =
box := IntBox{Value: size}
text := box.String()
fmt.Println("size=", size)
fmt.Println("text=", text)
fmt.Println("double=", box.Value*2)
}
package main
import "fmt"
// Generic shape: Box[T any] struct { Value T }
type IntBox struct {
Value int
}
func (box IntBox) String() string {
return fmt.Sprint(box.Value)
}
func main() {
var size =
box := IntBox{Value: size}
text := box.String()
fmt.Println("size=", size)
fmt.Println("text=", text)
fmt.Println("double=", box.Value*2)
}
generic struct
A generic struct can keep the same fields and methods while changing the stored value type. The trace uses a concrete integer box and shows the generic shape in a comment.