Created
August 8, 2022 14:18
-
-
Save valsteen/7f2d6486f02de85321b9904141310b81 to your computer and use it in GitHub Desktop.
Go: constraint a generic type to implement an interface with a pointer receiver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Demonstrates how to constraint a generic type to implement an interface with a pointer receiver | |
// inspired by this SO answer: https://stackoverflow.com/a/71444968 | |
import ( | |
"fmt" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
if res, err := ParseAll[Dummy]("1,2,3,4,5635,2,2,34,5"); err == nil { | |
// displays: [{ID:1} {ID:2} {ID:3} {ID:4} {ID:5635} {ID:2} {ID:2} {ID:34} {ID:5}] | |
fmt.Printf("%+v", res) | |
} else { | |
fmt.Println(err) | |
} | |
} | |
type FromString interface { | |
FromString(string) error | |
} | |
type Dummy struct { | |
ID int | |
} | |
func (id *Dummy) FromString(value string) error { | |
if res, err := strconv.Atoi(value); err == nil { | |
*id = Dummy{ID: res} | |
return nil | |
} else { | |
return err | |
} | |
} | |
func ParseAll[T any, PT interface { | |
*T | |
FromString | |
}](values string) ([]T, error) { | |
stringList := strings.Split(values, ",") | |
objs := make([]T, len(stringList)) | |
for i, s := range stringList { | |
var obj PT = &objs[i] | |
err := obj.FromString(s) | |
if err != nil { | |
return nil, err | |
} | |
} | |
return objs, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment