Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
package main
import (
"fmt"
"reflect"
)
// Subtractable is a type constraint that defines subtractable datatypes to be used in generic functions
type Subtractable interface {
~ int | int32 | int64 | float32 | float64 | uint | uint32 | uint64
@percybolmer
percybolmer / Go-1.18-TypeArgument.go
Last active January 27, 2022 19:09
Example Of how decide on the data type
package main
import (
"fmt"
"reflect"
)
// Subtractable is a type constraint that defines subtractable datatypes to be used in generic functions
type Subtractable interface {
int | int32 | int64 | float32 | float64 | uint | uint32 | uint64
// Moveable is a interface that is used to handle many objects that are moveable
type Moveable interface {
Move(int)
}
// Person is a person, implements Moveable
type Person struct {
Name string
}
func (p Person) Move(meters int) {
// Move is a generic function that takes in a Moveable and moves it
func Move[V Moveable](v V, meters int) {
v.Move(meters)
}
// Results is a array of results, the data types can be any
type Results[T any] []T
// Subtractable is a type constraint that defines subtractable datatypes to be used in generic functions
type Subtractable interface {
int | int32 | int64 | float32 | float64 | uint | uint32 | uint64
}
func main(){
var a int = 20
func main(){
var a int = 20
var b int = 10
result := Subtract(a, b)
var c float32 = 20.5
var d float32 = 10.3
result2 := Subtract[float32](c, d)
// Results is a array of results, reusing the type constraint Subtractable
type Results[T Subtractable] []T
var c float32 = 20.5
var d float32 = 10.3
result := Subtract(c, d)
result2 := Subtract[float32](c, d)
package main
import (
"fmt"
)
// Subtractable is a type constraint that defines subtractable datatypes to be used in generic functions
type Subtractable interface {
int | int32 | int64 | float32 | float64 | uint | uint32 | uint64
}
package main
import (
"fmt"
)
func main(){
var a int = 20
var b int = 10
// the compiler will infere the type used