add go examples

This commit is contained in:
Ringo Hoffmann committed 2026-07-16 10:57:43 +02:00
1 parent 6eef7e38a7
commit e81e018785
7 files changed
+118

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
module typestate-structs
go 1.26.5
+45
View File
@@ -0,0 +1,45 @@
package main
type LockedCredentialManager struct {
entries map[string]string
}
type UnlockedCredentialManager struct {
entries map[string]string
}
func NewCredentialManager() LockedCredentialManager {
return LockedCredentialManager{
entries: make(map[string]string),
}
}
func (m LockedCredentialManager) Unlock(masterSecret string) UnlockedCredentialManager {
return UnlockedCredentialManager{
entries: m.entries,
}
}
func (m UnlockedCredentialManager) Set(key string, secret string) {
panic("todo")
}
func (m UnlockedCredentialManager) Get(key string) (string, bool) {
panic("todo")
}
func (m UnlockedCredentialManager) Lock() LockedCredentialManager {
return LockedCredentialManager{
entries: m.entries,
}
}
func main() {
pw := NewCredentialManager()
unlocked := pw.Unlock("pssst")
unlocked.Set("foo", "bar")
_, _ = unlocked.Get("foo")
unlocked.Lock()
}
+3
View File
@@ -0,0 +1,3 @@
module typestate-interfaces
go 1.26.5
+54
View File
@@ -0,0 +1,54 @@
package main
import "errors"
type LockedCredentialManager interface {
Unlock(masterKey string) (UnlockedCredentialManager, error)
}
type UnlockedCredentialManager interface {
Lock() (LockedCredentialManager, error)
Set(key string, secret string) error
Get(key string) (string, error)
}
type credentialManager struct {
unlocked bool
entries map[string]string
}
func NewCredentialManager() LockedCredentialManager {
return &credentialManager{
entries: make(map[string]string),
}
}
func (t *credentialManager) Unlock(masterKey string) (UnlockedCredentialManager, error) {
if t.unlocked {
return nil, errors.New("already unlocked")
}
t.unlocked = true
return t, nil
}
func (t *credentialManager) Lock() (LockedCredentialManager, error) {
if !t.unlocked {
return nil, errors.New("already locked")
}
t.unlocked = false
return t, nil
}
func (t *credentialManager) Set(key string, secret string) error {
if !t.unlocked {
return errors.New("locked")
}
panic("todo")
}
func (t *credentialManager) Get(key string) (string, error) {
if !t.unlocked {
return "", errors.New("locked")
}
panic("todo")
}
File renamed without changes.
+7
View File
@@ -0,0 +1,7 @@
# Type Level Programming
## Sources
- https://www.emoses.org/posts/resolver-resolved-pattern/
- https://farazdagi.com/posts/2024-04-07-typestate-pattern/
- https://youtu.be/_ccDqRTx-JU
+6
View File
@@ -0,0 +1,6 @@
go 1.26.5
use (
./05-typestate-go-structs
./06-typestate-go-interfaces
)