Why composition perform that way?

package main

import (
"fmt"
)

type aki float64

func(a aki) String() string {
return fmt.Sprintf("%.2f C", a)
}

type di struct {
aki
name string
}

func main() {
ak := aki(5)
fmt.Println(ak)
d := di{7, "daria"}
fmt.Println(d)
}

why when I do fmt.Println(d) it does not print name field, and I have to write explicitly d.name to print out “daria”

If some method or field is not available on di, it will be dispatched to aki, since you haven’t implemented String() for di, akis gets used.

2 Likes

func (d di) String() string {
return fmt.Sprintf("%s %s", d.aki, d.name)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.