-1

I try to extend the base struct, like this:


import (
    "fmt"
)

type A struct {
    A bool
    C bool
}

type B struct {
    A
    B bool
}

func main() {
    fmt.Println("Hello, playground")
    a := A{
        A: false,
        C: false,
    }

    b := B{
        a,
        true,
    }

    fmt.Print(b)
}

But it creates inherit struct. The output of this code is: {{false false} true}

But I would like to get {false false true}

Is it possible?

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    "But I would like to get" --- it's an XY problem. Do you really want just to print it that way only, or there is some other reason you didn't reveal? – zerkms Jul 28 '21 at 09:34
  • 1
    "Is it possible?" No. Embedding is composition, not inheritance. You will fail mimicking inheritance. – Volker Jul 28 '21 at 09:34
  • Is `fmt.Print(b)` what you really want or are you just using it for testing? If you want to encode to JSON using `encoding/json`, `b` marshals with all top level keys `{"A":false,"C":false,"B":true}`. See: https://play.golang.org/p/S3pS1PU_0WY . – Grokify Jul 28 '21 at 09:48
  • @zerkms I would like to get struct like ```{ A bool B bool C bool }``` – Sergey Gorbunov Jul 28 '21 at 10:02
  • 1
    @SergeyGorbunov what _actual_ problem do you have with nesting? – zerkms Jul 28 '21 at 10:09
  • @zerkms I need to extend the struct to add some additional fields and send it via rmq. I can't use existed struct, because it is used in db model – Sergey Gorbunov Jul 28 '21 at 10:16

1 Answers1

4

There is no extension in the "classical" OOP sense, embedding a type in a struct will not add fields of the embedded struct but add a single field with a type being the embedded type, which can be referred to by the unqualified type name: b.A.

If you just want so that it gets printed like you want, you may implement the fmt.Stringer interface:

func (b B) String() string {
    return fmt.Sprintf("{%t %t %t}", b.A.A, b.C, b.B)
}

Then output would be like (try it on the Go Playground):

{false false true}

But that's the end of it.

icza
  • 389,944
  • 63
  • 907
  • 827