Skip to content

Instantly share code, notes, and snippets.

@powerslacker
Created March 17, 2018 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save powerslacker/fc274965286ce34887e5e424b9128a51 to your computer and use it in GitHub Desktop.
Save powerslacker/fc274965286ce34887e5e424b9128a51 to your computer and use it in GitHub Desktop.
interfaces FTW
// https://www.reddit.com/r/golang/comments/852i6m/about_to_switch_to_python_because_ive_hit_a_brick/?ref=share&ref_source=link
package main
import "errors"
const (
MonsterType = iota
CookingRecipeType
InventoryItemType
)
type datastore struct {
// mock db
}
type Row struct {
// mock
}
func (d *datastore) Query(q string, args ...interface{}) Row {
// mock
return Row{}
}
func (Row) Scan(args ...interface{}) {
// mock
return
}
var db = datastore{}
type AdminResource interface {
GetDetails(int)
}
type MonsterResource struct {
TotalHP int
CurrentHP int
}
func (m MonsterResource) GetDetails(resid int) {
db.Query("SELECT total_hp, current_hp FROM monsters WHERE resource_id = ?", resid).Scan(
&m.TotalHP, &m.CurrentHP)
}
func GetResource(id int) AdminResource {
var resID int
var resType int
db.Query("SELECT id, resource_type FROM admin_resources WHERE id = ?", id).Scan(
&resID, &resType)
out, err := GetResourceType(resType)
if err != nil {
// handle err
}
out.GetDetails(resID)
return out
}
func GetResourceType(resType int) (AdminResource, error) {
switch resType {
case MonsterType:
return MonsterResource{}, nil
case CookingRecipeType:
// do something
case InventoryItemType:
// do something
}
return nil, errors.New("invalid resource type")
}
func main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment