Embedded methods doubt

Hello all,
how i do an generic embedded method?

in the next e.g.:

package main

import (

type AType struct {
	Name string

func (a AType) String() string {
	str, _ := json.Marshal(&a)
	return string(str)

type Btype struct {
	OtherString string

func main() {
	b := Btype{AType: AType{"xname"}, OtherString: "other"}

the console output is


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

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}

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