tim-montague
tim-montague

Reputation: 17362

Partially embedded struct

I can embed type A into B.

type A struct {
  R int64
  S int64
}

type B struct {
  A
}

But how do I embed just a single field?

type B struct {
  A.R // does not work
}

Upvotes: 0

Views: 644

Answers (3)

tim-montague
tim-montague

Reputation: 17362

This is the best solution I have now...

type A struct {
  R int64
  S int64
}

type B struct {
  R A
}

And then during implementation...

&B{
 R: &A{
   R,
   // S, - ideally we would not be able to pass in `S`
 }
}

I don't like this solution, because we can still pass in S...


Update: Based on @HymnsForDisco answer this could be coded as...

// A type definition could be used `type AR int64`,
//   instead of a type alias (below), but that would
//   require us to create and pass the `&AR{}` object,
//   to `&A{}` or `&B{}` for the `R` field.
type AR = int64

type A struct {
  R AR
  S int64
}

type B struct {
  R AR
}

And implemented as...

&B{
  R,
}

Upvotes: 0

Hymns For Disco
Hymns For Disco

Reputation: 8395

Let's suppose your two struct data types A and B.

If you want A and B to both have a field named F of type T, you can do it like so

type (
    A struct {
        F T
    }

    B struct {
        F T
    }
)

If you wish to change type T in only one location in the source, you can abstract it like so

type (
    T = someType

    A struct {
        F T
    }

    B struct {
        F T
    }
)

If you wish to change the name of F in only one location in the source, you can abstract it like so

type (
    myField struct {
        F T
    }

    A struct {
        myField
    }

    B struct {
        myField
    }
)

If you have multiple extricable fields to abstract, they must be abstracted individually like so

type (
    myField1 struct {
        F1 T1
    }
    myField2 struct {
        F2 T2
    }
    
    A struct {
        myField1
        myField2
    }
    
    B struct {
        myField1
    }
)

Upvotes: 3

BigCore
BigCore

Reputation: 517

You can't embed a single field. You can only embed an entire type.

If you want to embed a single field, you'll need to create a new type that contains only that field, and embed that type instead:

type R struct {
  R int64
}

type B struct {
  R
}

Upvotes: 0

Related Questions