In Go, encapsulation and access control can be enforced in embedded structs using a combination of naming conventions and field visibility modifiers. Here are some steps to follow:
Create a struct that represents the embedded struct. This struct will hold the data and methods specific to the embedded struct. Let's call it embeddedStruct
.
Define the fields and methods for the embeddedStruct
struct, keeping in mind the encapsulation requirements.
Within the parent struct, define an embedded field of type embeddedStruct
. This creates an "is-a" relationship between the parent struct and the embedded struct.
Make the field of the embedded struct private by starting its name with a lowercase letter. This ensures that the field is not directly accessible from outside the parent struct.
Here's an example implementation:
// embeddedStruct represents the embedded struct with encapsulated fields and methods.
type embeddedStruct struct {
privateField int
}
// PublicMethod is a method of the embedded struct.
func (es *embeddedStruct) PublicMethod() {
// Access to the privateField is allowed here.
es.privateField = 10
}
// ParentStruct represents the parent struct embedding the embeddedStruct.
type ParentStruct struct {
embeddedStruct
publicField int
}
func main() {
ps := ParentStruct{}
// Access to the embedded struct's privateField is not allowed here.
// ps.privateField = 5 // This will cause a compilation error.
// Access to the embedded struct's privateField is allowed via public methods.
ps.PublicMethod() // Successfully sets privateField to 10
// The parent struct's publicField can be directly accessed.
ps.publicField = 20
}
In this example, ParentStruct
embeds the embeddedStruct
, allowing access to publicField
directly but restricting access to privateField
. The publicField
can be accessed and modified directly. However, access to privateField
is only allowed through PublicMethod()
.