Simple Note about Composite of Golang

83 阅读1分钟

There is no inheritance like other object oriented language in golang, golang uses composite to implement code and function reuse purpose. When there are same named members in a struct and its composited struct, how to assign to members of its composited struct?

package main

import "fmt"

type Base struct {
	m string
	s string
}

func (b *Base) Setm(m string) {
	b.m = m
}

type Material struct {
	Base
	m string
	s string
}

func main() {
	m := &Material{m: "material_m", s: "material_s"}
	fmt.Println(m.m, m.s, m.Base.m, m.Base.s)
        
	m.Setm(m.m)
	fmt.Println(m.m, m.s, m.Base.m, m.Base.s)
}

Output:

material_m material_s  
material_m material_s material_m 

m.Setm(m.m) assigns to m.Base.m actually.