Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
type ValuesRequest struct {
Values []int `json:"values"`
}
func CalculateHighest(w http.ResponseWriter, r *http.Request) {
// Declare a valuerequest
var vr ValuesRequest
// Decode and respond with error incase it fails
err := json.NewDecoder(r.Body).Decode(&vr)
//go:build go1.18
// +build go1.18
package fuzz
import (
"net/url"
"reflect"
"testing"
)
// Move is a generic function that takes in a Moveable and moves it
// Subtractable is placed infront of Moveable instead
func Move[S Subtractable, V Moveable[S]](v V, distance S, meters S) S {
v.Move(meters)
return Subtract(distance, meters)
}
// You can now do this instead of having to define Person
newDistanceLeft := Move[float64](p, float64(distanceLeft), 5)
func main(){
// John is travelling to his Job
// His car travel is counted in int
// And his walking in Float32
p := Person[float64]{Name: "John"}
c := Car[int]{Name: "Ferrari"}
// John has 100 miles to his job
milesToDestination := 100
// Move is a generic function that takes in a Generic Moveable and moves it
func Move[V Moveable[S], S Subtractable](v V, distance S, meters S) S {
v.Move(meters)
return Subtract(distance, meters)
}
func main(){
// John is travelling to his Job
// His car travel is counted in int
// And his walking in Float32
p := Person[float64]{Name: "John"}
c := Car[int]{Name: "Ferrari"}
}
// Person is a struct that accepts a type definition at initialization
// And uses that Type as the data type for meters as input
func (p Person[S]) Move(meters S) {
fmt.Printf("%s moved %d meters\n", p.Name, meters)
}
func (c Car[S]) Move(meters S) {
fmt.Printf("%s moved %d meters\n", c.Name, meters)
}
// Car is a Generic Struct with the type S to be defined
type Car[S Subtractable] struct {
Name string
}
// Person is a Generic Struct with the type S to be defined
type Person[S Subtractable] struct {
Name string
}
// Moveable is a interface that is used to handle many objects that are moveable
// To implement this interface you need a Generic Type with a Constraint of Subtractable
type Moveable[S Subtractable] interface {
Move(S)
}
@percybolmer
percybolmer / Go-1.18-TypeConstraintInInterfaceBypass.go
Last active January 27, 2022 19:09
This code is not working because type constraint
// Moveable is a interface that is used to handle many objects that are moveable
type Moveable interface {
Move(Subtractable)
}
// Person is a person, implements Moveable
type Person struct {
Name string
}