Created
March 17, 2018 16:40
-
-
Save powerslacker/fc274965286ce34887e5e424b9128a51 to your computer and use it in GitHub Desktop.
interfaces FTW
This file contains 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
// 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