Methods
This Go program demonstrates the usage of methods with both value receivers and pointer receivers on a struct.
Let's go through each part of the code with inline comments and additional explanations:
Output
Explanation:
A
rect
struct is defined with two fields:width
andheight
.The
area
method is defined with a pointer receiver (*rect
). It calculates and returns the area of the rectangle.The
perim
method is defined with a value receiver (rect
). It calculates and returns the perimeter of the rectangle.In the
main
function:An instance
r
of therect
struct is created with field values 10 and 5.The
area
andperim
methods are called on the struct, and the results are printed.A pointer
rp
to therect
struct is created.The
area
andperim
methods are called using the pointer, and the results are printed.
Using a pointer receiver in a method allows modifications to the original struct, while using a value receiver creates a copy of the struct for the method to work with, leaving the original unchanged.
Last updated