Go OOP sample
- main.go
/*
* Author, Copyright: Oleg Borodin <onborodin@gmail.com>
*/
package main
import (
"fmt"
"objgo/calc"
)
func main() {
i := calc.New()
i.Add("some", 10)
i.Add("bare", 10)
i.Add("foo", 20)
i.Delete("foo")
i.Print()
fmt.Println("OK")
}
- index.go
*
* Author, Copyright: Oleg Borodin <onborodin@gmail.com>
*/
package calc
import (
"fmt"
"errors"
)
type Index struct {
items map[string]int
sum int
}
type Indexer interface {
Add(name string, cost int) (error)
Delete(name string)
Print()
}
func (i *Index) Add(name string, cost int) error {
if _, have := i.items[name]; !have {
i.items[name] = cost
i.sum += cost
return nil
}
return errors.New(fmt.Sprintf("item %s already exist", name))
}
func (i *Index) Delete(name string) {
if _, have := i.items[name]; have {
i.sum -= i.items[name]
delete(i.items, name)
}
}
func (i Index) Print() {
for key, value := range i.items {
fmt.Println("name:", key, "const:", value)
}
fmt.Println("sum:", i.sum)
}
func New() Indexer {
return &Index{
items: map[string]int{},
sum: 0,
}
}
Output
$ go run obj.go
name: some cost: 10
name: bare cost: 10
sum: 20
OK