Last active
April 1, 2021 02:07
-
-
Save xeoncross/036fe248d39acaa295dfd77f8e3b8580 to your computer and use it in GitHub Desktop.
Example of using struct enbeding to implement an interface: https://play.golang.org/p/9RAY8RI7_N7
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 A struct { | |
B string | |
} | |
func (a *A) Value() string { | |
return a.B | |
} | |
type C struct { | |
*A | |
} | |
// C does not implement the interface, but A does and C contains it | |
//func (c *C) Value() string { | |
// return c.A.Value() | |
//} | |
type Z interface { | |
Value() string | |
} | |
var _ Z = (*C)(nil) // The compiler checks that C implements Z (via A) here | |
func main() { | |
a := &A{"hello"} | |
c := &C{a} | |
fmt.Println(c.Value()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment