Last active
September 11, 2024 22:00
-
-
Save MWhyte/290ca53e891f7645ee53f3c4dac32ecc to your computer and use it in GitHub Desktop.
A Simple example of how to use interfaces in go
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" | |
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