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
}
CodePudding user response:
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 (
type A struct {
F T
}
type 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 (
type T = someType
type A struct {
F T
}
type 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 (
type myField struct {
F T
}
type A struct {
myField
}
type 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
}
type A struct {
myField1
myField2
}
type B struct {
myField1
}
)
CodePudding user response:
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
}
CodePudding user response:
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...
type AR = int64
type A {
R AR
S int64
}
type B struct {
R AR
}
And implemented as...
&B{
R
}