Created
November 12, 2022 23:48
-
-
Save oslyak/d6db7fa64f70fa7f08cfb87675b96e35 to your computer and use it in GitHub Desktop.
Generics type conversion example
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 | |
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