config.Config has a method func String(string) string
and I want to mix those methods to my Type Config
1. it is ok when
// type Config struct
type Config struct {
// a struct has many methods
config.Config
Path string
}
// new and call string method
var a Config = &Config{}
a.String("test")
// type Config struct
type (
Configure config.Config
Config struct {
Configure
Path string
}
)
// new and call string method
var a Config = &Config{}
// error, can not call `String()`
a.String("test")
It's well put by https://go101.org/article/type-system-overview.html:
a new defined type and its respective source type in type definitions are two distinct types.
This works:
package main
import(
"fmt"
)
type MyType struct {
Id int
}
func (mt *MyType)Method() {
fmt.Printf("Method called %d
", mt.Id)
}
type MyOtherType MyType
func main(){
mt := &MyType{Id:3}
mt.Method()
//mt2 := &MyOtherType{Id:5}
//mt2.Method()
}
But if you uncomment mt2.Method()
, you get an error:
mt2.Method undefined (type *MyOtherType has no field or method Method)
Composition works differently. A struct does get the methods of the structs of which it's composed:
package main
import (
"fmt"
)
type MyType struct {
Id int
}
func (mt *MyType) Method() {
fmt.Printf("Method called %d
", mt.Id)
}
type MyOtherType struct {
MyType
}
func main() {
mt := &MyType{Id: 3}
mt.Method()
mt2 := &MyOtherType{MyType{Id: 5}}
mt2.Method()
}
That's the magic of type composition.
$ go run t.go
Method called 3
Method called 5