What difference there is when you access to another struct by value or by a pointer?
When should be used each one of them?
type foo_ struct {
st uint8
nd uint8
}
type bar struct {
rd uint8
foo foo_
}
type barP struct {
rd uint8
foo *foo_
}
If you declare or allocate a variable of
type bar, you reserve and initialize to zero memory for bothrd uint8andfoo foo_. There is always one variable oftype foo_embedded in a variable oftype bar.If you declare or allocate a variable of
type barP, you reserve and initialize to zero memory for bothrd uint8andfoo *foo_. A zero value pointer is anilpointer. No variable oftype foo_is allocated; you must do that separately. There is either zero (foo == nil) or one variable oftype foo_pointed to by a variable oftype barP. A variable oftype barPmay point to the same variable oftype foo_as other variables oftype barP, sharing the same copy of the variable oftype foo_. A change to a shared copy is seen by all variables that point to it.Which one to use depends on the properties of
type barversustype barP. Which type more closely reflects the problem that you are trying to solve?For example, consider this invoice problem. We always have a billing address; we are always going to ask for our money. However, we often ship to the billing address, but not always. If the shipping address is
nil, use the billing address. Otherwise, use a separate shipping address. We have two warehouses, and we always ship from one or the other. We can share the two warehouse locations. Since we don’t send an invoice until the order is shipped from the warehouse, the warehouse location will never benil.