Last active
March 15, 2020 20:53
-
-
Save halkyon/ba934774e76ca4d08c790f1b259d522b to your computer and use it in GitHub Desktop.
Simple example of an interface in Go using a "loader" interface with memory and disk as implementations
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
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
type loader interface { | |
Read() ([]byte, error) | |
Write([]byte) error | |
} | |
type memory struct { | |
data []byte | |
} | |
type disk struct { | |
path string | |
} | |
func (d *disk) Read() ([]byte, error) { | |
data, err := ioutil.ReadFile(d.path) | |
if err != nil { | |
return nil, err | |
} | |
return data, nil | |
} | |
func (d *disk) Write(data []byte) error { | |
return ioutil.WriteFile(d.path, data, 0600) | |
} | |
func (d *memory) Read() ([]byte, error) { | |
return d.data, nil | |
} | |
func (m *memory) Write(data []byte) error { | |
m.data = data | |
return nil | |
} | |
func Write(l loader, data []byte) error { | |
return l.Write(data) | |
} | |
func Read(l loader) ([]byte, error) { | |
return l.Read() | |
} | |
func doMemory() { | |
m := &memory{} | |
Write(m, []byte("something")) | |
data, err := Read(m) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Read of in-memory data:", string(data)) | |
} | |
func doDisk() { | |
testFilePath := "somefile.txt" | |
d := &disk{path: testFilePath} | |
defer os.Remove(testFilePath) | |
Write(d, []byte("somethingelse")) | |
data, err := Read(d) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Read of disk data:", string(data)) | |
} | |
func main() { | |
doMemory() | |
doDisk() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment