Created
September 15, 2013 12:26
-
-
Save karlseguin/6570372 to your computer and use it in GitHub Desktop.
String interning in Golang
This file contains hidden or 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
package intern | |
import ( | |
"sync" | |
) | |
type Pool struct { | |
sync.RWMutex | |
lookup map[string]string | |
} | |
func New() *Pool { | |
return &Pool{lookup: make(map[string]string)} | |
} | |
func (p *Pool) Intern(s string) string { | |
p.RLock() | |
ss, exists := p.lookup[s] | |
p.RUnlock() | |
if exists { return ss } | |
p.Lock() | |
defer p.Unlock() | |
ss, exists = p.lookup[s] | |
if exists { return ss } | |
p.lookup[s] = s | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment