Why do programmers use methods in Go instead of just functions?
Think about how methods help group actions with the data they work on.
Methods let you attach functions to types, so you can call them directly on values of that type. This keeps related code together and makes programs easier to read and maintain.
What is the output of this Go program?
package main import "fmt" type Person struct { name string } func (p Person) greet() string { return "Hello, " + p.name } func main() { p := Person{name: "Anna"} fmt.Println(p.greet()) }
Look at how the method uses the receiver to access the name field.
The method greet() is called on the Person value p. It returns "Hello, " plus the name field, which is "Anna".
Consider this Go code. Why does the method not change the original struct's field?
package main import "fmt" type Counter struct { count int } func (c Counter) increment() { c.count++ } func main() { c := Counter{count: 5} c.increment() fmt.Println(c.count) }
Think about how Go passes the receiver to the method.
Methods with value receivers get a copy of the struct. Changes inside the method affect only the copy, not the original.
Which option shows the correct way to declare a method named describe for a struct type Book in Go?
Remember method syntax requires receiver in parentheses and a return type if returning a value.
Option A correctly declares a method with receiver b Book, method name describe, and return type string.
Given a struct Account with a method Deposit that adds money to the balance, which method receiver choice is best and why?
Think about whether the method needs to change the original data or just read it.
To update the balance inside the method, the receiver must be a pointer so changes affect the original struct.