-
-
Save deinspanjer/14b34f4c2e05a9be7c5c5ce941c34ddc to your computer and use it in GitHub Desktop.
Example of cross-package interfaces in golang
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 a | |
import "fmt" | |
type Sayer interface { | |
Say() string | |
} | |
type Formal struct{} | |
func (p Formal) Greet(s interface{Sayer}) string { | |
return fmt.Sprintf("Hello, %s", s.Say()) | |
} |
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 b | |
import "fmt" | |
type Sayer interface { | |
Say() string | |
} | |
type Casual struct{} | |
func (p Casual) Greet(s interface{Sayer}) string { | |
return fmt.Sprintf("Hey %s!", s.Say()) | |
} |
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 greet | |
type Sayer interface { | |
Say() string | |
} | |
type Greeter interface { | |
Greet(s interface{Sayer}) string | |
} | |
func Greet(g interface{Greeter}, i Sayer) string { | |
return g.Greet(i) | |
} |
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 ( | |
"log" | |
"test/a" | |
"test/b" | |
"test/greet" | |
) | |
type Who struct { | |
to string | |
} | |
func (w Who) Say() string { | |
return w.to | |
} | |
type Bad struct { | |
to string | |
} | |
func (w Bad) Say(exclaim bool) string { | |
said := w.to | |
if exclaim { | |
said += "!!!" | |
} | |
return said | |
} | |
func main() { | |
log.Println("Testing...") | |
a := a.Formal{} | |
b := b.Casual{} | |
w := &Who{ | |
to:"world", | |
} | |
x := &Bad{ | |
to:"world", | |
} | |
log.Println(greet.Greet(a, w)) | |
log.Println(greet.Greet(b, w)) | |
//log.Println(greet.Greet(b, x)) | |
} |
In your method signatures, just use the interface types themselves. As you have them now, they declare new anonymous types that embed the type you actually care about.
E.g., instead of Greet(s interface{Sayer})
, you would just use Greet(s Sayer)
. And instead of Greet(g interface{Greeter}, i Sayer)
you would just use Greet(g Greeter, i Sayer)
.
Thanks. It's very helpful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Good example