Skip to content

Instantly share code, notes, and snippets.

@oslyak
Created November 12, 2022 23:48
Show Gist options
  • Save oslyak/d6db7fa64f70fa7f08cfb87675b96e35 to your computer and use it in GitHub Desktop.
Save oslyak/d6db7fa64f70fa7f08cfb87675b96e35 to your computer and use it in GitHub Desktop.
Generics type conversion example
package main
import (
"fmt"
)
type User struct {
FullName string
Removed bool
}
type Account struct {
Name string
Removed bool
}
type Scanner[T User | Account] interface {
Scan()
*T
}
type Model interface {
User | Account
}
func (user *User) Scan() {
user.FullName = `changed in scan method`
user.Removed = true
}
func (account *Account) Scan() {
account.Name = `changed in scan method`
account.Removed = true
}
func setRemovedState[T Model, PT Scanner[T]](state bool) *T {
var obj T
pointer := PT(&obj)
pointer.Scan() // calling method on non-nil pointer
return &obj
}
func main() {
user := setRemovedState[User](true)
account := setRemovedState[Account](true)
fmt.Printf("User: %v\n", *user)
fmt.Printf("Account: %v\n", *account)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment