Methods and embedding
- Go course
- Beginner
- Lesson 78/90
- 4 min
Learn how embedded struct methods are promoted.
Methods and embedding
The methods of an embedded struct are also promoted to the outer struct; the outer type calls them as if they were its own:
type Kayitci struct{ Onek string }
func (k Kayitci) Logla(m string) { fmt.Println(k.Onek + m) }
type Servis struct {
Kayitci
Ad string
}
s := Servis{Kayitci{"[api] "}, "sepet"}
s.Logla("başladı") // [api] başladıThis way shared behavior is reused without inheritance.
Shadowing and wrapping
The outer type can extend behavior by defining a method with the same name and calling the embedded one from inside:
func (s Servis) Logla(m string) {
s.Kayitci.Logla(s.Ad + ": " + m)
}
s.Logla("başladı") // [api] sepet: başladıThis pattern is Go's counterpart to "calling the superclass method" in other languages, but explicit and visible.
Practice Wrapped logger
Write the Kayitci type above and Servis, which embeds it; Servis's own Logla method prepends s.Ad + ": " to the message and calls the embedded Logla. Run Servis{Kayitci{"[api] "}, "sepet"}.Logla("başladı").
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Kayitci struct{ Onek string }
func (k Kayitci) Logla(m string) { fmt.Println(k.Onek + m) }
type Servis struct {
Kayitci
Ad string
}
func (s Servis) Logla(m string) {
s.Kayitci.Logla(s.Ad + ": " + m)
}
func main() {
Servis{Kayitci{"[api] "}, "sepet"}.Logla("başladı")
}Expected output
[api] sepet: başladı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If Servis defines its own <code>Logla</code> method, which does <code>s.Logla("x")</code> call?
- Both
- A compile error
- Servis's own Logla Correct answer
- Kayitci's Logla
Explanation: The outer type's method shadows the embedded one; the embedded method can still be called with s.Kayitci.Logla("x").
2 Call the embedded method
func (s Servis) Logla(m string) {
s.____.Logla(s.Ad + ": " + m)
}
func (s Servis) Logla(m string) {
s.Kayitci.Logla(s.Ad + ": " + m)
}
Explanation: The embedded type's name gives full-path access to its method.
3 Call and result
| Term | Meaning |
|---|---|
s.Logla (Servis'te yoksa) |
Kayitci.Logla |
s.Logla (Servis'te varsa) |
Servis.Logla |
s.Kayitci.Logla |
Always the embedded one |
Embedding |
Reuse |