mirror of
https://github.com/chai2010/advanced-go-programming-book.git
synced 2025-05-24 12:32:21 +00:00
54 lines
681 B
Go
54 lines
681 B
Go
package main
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
type ObjectId int32
|
|
|
|
var refs struct {
|
|
sync.Mutex
|
|
objs map[ObjectId]interface{}
|
|
next ObjectId
|
|
}
|
|
|
|
func init() {
|
|
refs.Lock()
|
|
defer refs.Unlock()
|
|
|
|
refs.objs = make(map[ObjectId]interface{})
|
|
refs.next = 1000
|
|
}
|
|
|
|
func NewObjectId(obj interface{}) ObjectId {
|
|
refs.Lock()
|
|
defer refs.Unlock()
|
|
|
|
id := refs.next
|
|
refs.next++
|
|
|
|
refs.objs[id] = obj
|
|
return id
|
|
}
|
|
|
|
func (id ObjectId) IsNil() bool {
|
|
return id == 0
|
|
}
|
|
|
|
func (id ObjectId) Get() interface{} {
|
|
refs.Lock()
|
|
defer refs.Unlock()
|
|
|
|
return refs.objs[id]
|
|
}
|
|
|
|
func (id ObjectId) Free() interface{} {
|
|
refs.Lock()
|
|
defer refs.Unlock()
|
|
|
|
obj := refs.objs[id]
|
|
delete(refs.objs, id)
|
|
|
|
return obj
|
|
}
|