Welcome to your Go programming journey! Today, we're diving into one of the fundamental concepts - Go Methods and Functions. Let's get started! 🏃♂️
A function is a set of instructions that performs a specific task. Go functions have the following characteristics:
Here's a simple function example:
func HelloWorld() {
fmt.Println("Hello, World!")
}In this example, we've defined a function called HelloWorld that prints "Hello, World!" to the console when called.
Methods in Go are functions associated with a struct or interface. They provide a way to operate on the struct's fields.
type Point struct {
X int
Y int
}
func (p *Point) Distance(p2 *Point) float64 {
return math.Sqrt(float64(math.Pow(float64(p2.X-p.X), 2) + math.Pow(float64(p2.Y-p.Y), 2)))
}In this example, we've defined a Point struct and a method called Distance. The Distance method takes another Point as an argument and calculates the distance between the two points.
Note that the receiver p *Point is a pointer to the Point struct. This allows the method to modify the struct's fields if needed.
The main difference between methods and functions is that methods are associated with a specific data type (struct or interface), while functions are standalone entities.
Here's a quiz to test your understanding:
Which of the following functions can operate on a `Point` struct?
Stay tuned for more Go lessons, where we'll explore more about methods, functions, and their practical applications! 🚀