Skip to content

Instantly share code, notes, and snippets.

@virgild
Created August 28, 2018 17:07
Show Gist options
  • Save virgild/466fd566c2308dbf1689358586a00793 to your computer and use it in GitHub Desktop.
Save virgild/466fd566c2308dbf1689358586a00793 to your computer and use it in GitHub Desktop.
I want generics!
package main
import "fmt"
type Account struct {
Name string
balance int64
}
func (a *Account) Balance() int64 {
return a.balance
}
type USDAccount struct {
name string
balance int64
stateOrigin string
}
func (a *USDAccount) Name() string {
return a.name
}
func (a *USDAccount) Balance() int64 {
return a.balance
}
type CADAccount struct {
name string
balance int64
provinceOrigin string
}
func (a *CADAccount) Name() string {
return a.name
}
func (a *CADAccount) Balance() int64 {
return a.balance
}
type WithBalance interface {
Name() string
Balance() int64
}
func PrintAccounts(accounts []WithBalance) {
for _, acc := range accounts {
fmt.Printf("%s = %d\n", acc.Name(), acc.Balance())
}
}
func main() {
us_accounts := []*USDAccount{}
us_accounts = append(us_accounts, &USDAccount{name: "USA account 1", balance: 0})
us_accounts = append(us_accounts, &USDAccount{name: "USA account 2", balance: 0})
cad_accounts := []*CADAccount{}
cad_accounts = append(cad_accounts, &CADAccount{name: "CAD account 1", balance: 0})
cad_accounts = append(cad_accounts, &CADAccount{name: "CAD account 2", balance: 0})
PrintAccounts(us_accounts)
PrintAccounts(cad_accounts)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment