Skip to content

Instantly share code, notes, and snippets.

@MWhyte
Last active September 11, 2024 22:00
Show Gist options
  • Save MWhyte/290ca53e891f7645ee53f3c4dac32ecc to your computer and use it in GitHub Desktop.
Save MWhyte/290ca53e891f7645ee53f3c4dac32ecc to your computer and use it in GitHub Desktop.
A Simple example of how to use interfaces in go
package main
import "fmt"
type DataSource interface {
Connect() error
Disconnect() error
}
type Postgres struct {
name string
}
func (p *Postgres) Connect() error {
fmt.Println("Connected to Postgres")
return nil
}
func (p *Postgres) Disconnect() error {
fmt.Println("Disconnected from Postgres")
return nil
}
type MySQL struct {
name string
}
func (m *MySQL) Connect() error {
fmt.Println("Connected to MySQL")
return nil
}
func (m *MySQL) Disconnect() error {
fmt.Println("Disconnected from MySQL")
return nil
}
func main() {
NewDao(&Postgres{
name: "Postgres",
})
NewDao(&MySQL{
name: "MySQL",
})
}
func NewDao(p DataSource) {
fmt.Println("Creating new DAO with name: ", p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment