Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
// We define the Type parameter V, which is a int, int32 or float32
// We also say that function parameter a and b has the data type of V
// We then make the function return V
func Subtract[V int | int32 | float32 ](a, b V) V {
return a - b
}
// We define the Type parameter V, which is a int
// We also say that function parameter a and b has the data type of V
// We then make the function return V
func Subtract[V int](a, b V) V {
return a - b
}
// We define the Type parameter V, which is a int
func Subtract[V int](a, b int) int {
return a - b
}
@percybolmer
percybolmer / Go-1.18subtract.go
Created January 9, 2022 13:41
A subtraction with integers
func Subtract(a, b int) int {
return a - b
}
@percybolmer
percybolmer / Go-1.18-SubtractGeneric.go
Created January 9, 2022 13:29
A generic subtract function
func main(){
var a int = 20
var b int = 10
var c float32 = 20
var d float32 = 10.5
result := Subtract(a, b)
// Here we tell the function that the input is a float32 data type, so expect the output parameter to be float32
resultfloat := Subtract[float32](c, d)
@percybolmer
percybolmer / Go-1.18-SubtractRegular.go
Last active January 9, 2022 13:27
go.1.18 subtract regular
func main(){
var a int = 20
var b int = 10
var c float32 = 20
var d float32 = 10.5
result := Subtract(a, b)
// We need to cast data type into int here
resultfloat := Subtract(int(c), int(d))
@percybolmer
percybolmer / replacedirectiveingo.mod
Created January 9, 2022 08:20
Replace directive in go.mod
module github.com/programmingpercy/mymodule
replace github.com/programmingpercy/mymodule => /home/users/percy/experimental/mymodule
require (
github.com/programmingpercy/mymodule v1.0.0
)
package main
import (
"fmt"
)
func main() {
intvalues := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
int64values := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
float64values := []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
@percybolmer
percybolmer / Go-1.18-SummaryWithoutGeneric.go
Last active January 1, 2022 20:37
A summary example without generics
package main
import (
"fmt"
)
func main() {
intvalues := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
int64values := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
float64values := []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
@percybolmer
percybolmer / Copilot shuffle generated-fixed.go
Created December 21, 2021 09:00
A fix for its function
func (d Deck) Shuffle() {
rand.Seed(time.Now().UnixNano())
for i := range d {
j := rand.Intn(len(d) - 1)
d[i], d[j] = d[j], d[i]
}
}