bushi
(Bushi)
June 10, 2016, 8:42pm
1
Hello all,
how i do an generic embedded method?
in the next e.g.:
package main
import (
"encoding/json"
"fmt"
)
type AType struct {
Name string
}
func (a AType) String() string {
str, _ := json.Marshal(&a)
return string(str)
}
type Btype struct {
AType
OtherString string
}
func main() {
b := Btype{AType: AType{"xname"}, OtherString: "other"}
fmt.Println(b)
}
the console output is
{"xname"}
but i expect
{"xname", "other"}
i know i can overload the method in the b struct, but how i do a generic method in AType for use in all child structs
dfc
(Dave Cheney)
June 11, 2016, 2:53am
2
You cannot. There is no mechanism for one type embedded in another to be aware of the fact it is embedded.
You may have wanted to embed the structure with a field name then if you declare
type Btype struct {
Astruct AType
OtherString string
}
with the assignment b := Btype{Astruct: AType{“xname”}, OtherString: “other”}
the output is close to what you asked {{“Name”:“xname”} other}
system
(system)
Closed
September 9, 2016, 8:09am
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.