0
0
Goprogramming~5 mins

Defining methods in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a method in Go?
A method in Go is a function with a special receiver argument. It is like a function tied to a specific type, allowing you to call it using the dot notation on values of that type.
Click to reveal answer
intermediate
How do you define a method with a pointer receiver in Go?
You define a method with a pointer receiver by specifying the receiver as a pointer type in parentheses before the method name, for example:
func (p *Person) UpdateName(newName string) { p.Name = newName }
This allows the method to modify the original value.
Click to reveal answer
intermediate
What is the difference between a value receiver and a pointer receiver in Go methods?
A value receiver gets a copy of the value, so changes inside the method do not affect the original. A pointer receiver gets the address, so changes inside the method affect the original value.
Click to reveal answer
intermediate
Can methods be defined on any type in Go?
No, methods can only be defined on named types declared in the same package. You cannot define methods on built-in types or types from other packages.
Click to reveal answer
beginner
Example: Define a method called Greet for a struct Person that prints a greeting message.
<pre>package main

import "fmt"

type Person struct { Name string }

func (p Person) Greet() {
    fmt.Println("Hello, my name is", p.Name)
}</pre>
Click to reveal answer
What does the receiver in a Go method specify?
AThe type the method belongs to
BThe return type of the method
CThe package where the method is defined
DThe name of the method
Which receiver type allows a method to modify the original value?
AValue receiver
BInterface receiver
CConstant receiver
DPointer receiver
Can you define a method on the built-in type int in Go?
ANo, never
BYes, always
COnly if int is declared in your package
DOnly if int is a pointer
How do you call a method named Print on a variable p of type Person?
APrint(p)
Bp.Print()
CPerson.Print(p)
DPrint.Person(p)
What happens if you define a method with a value receiver and modify the receiver inside the method?
AThe program will not compile
BThe original value is changed
COnly the copy inside the method changes
DThe method runs twice
Explain how to define a method in Go and the role of the receiver.
Think about how methods are like functions tied to a type.
You got /4 concepts.
    Describe the difference between pointer and value receivers and when to use each.
    Consider if you want the method to change the original data or not.
    You got /4 concepts.