0
0
Goprogramming~10 mins

Method call behavior in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to call the method on the struct instance.

Go
type Person struct {
    name string
}

func (p Person) Greet() string {
    return "Hello, " + p.name
}

func main() {
    p := Person{name: "Alice"}
    greeting := p.[1]()
    fmt.Println(greeting)
}
Drag options to blanks, or click blank then click option'
AHello
Bgreet
CSayHello
DGreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase method name which causes a compile error.
Calling a method name that does not exist.
2fill in blank
medium

Complete the code to call the pointer receiver method correctly.

Go
type Counter struct {
    count int
}

func (c *Counter) Increment() {
    c.count++
}

func main() {
    c := Counter{count: 0}
    [1].Increment()
    fmt.Println(c.count)
}
Drag options to blanks, or click blank then click option'
A*c
Bc
C&c
DCounter
Attempts:
3 left
💡 Hint
Common Mistakes
Calling pointer receiver method on a value type variable without &.
Using *c which is invalid syntax here.
3fill in blank
hard

Fix the error in calling the method with pointer receiver on a pointer variable.

Go
type Item struct {
    value int
}

func (i *Item) Double() {
    i.value *= 2
}

func main() {
    item := &Item{value: 5}
    [1].Double()
    fmt.Println(item.value)
}
Drag options to blanks, or click blank then click option'
A*item
Bitem
C&item
Ditem.value
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to dereference pointer variable before calling method.
Using &item which is pointer to pointer, invalid here.
4fill in blank
hard

Fill both blanks to create a map with keys as strings and values as the length of those strings, filtering only words longer than 3 characters.

Go
words := []string{"go", "code", "chat", "ai"}
lengths := map[string]int{
    [1]: [2]([1]),
}

for _, word := range words {
    if len(word) > 3 {
        lengths[word] = len(word)
    }
}
fmt.Println(lengths)
Drag options to blanks, or click blank then click option'
Aword
Bwords
Clen
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using the slice variable words as key instead of word.
Using a non-existent method length() instead of len().
5fill in blank
hard

Fill all three blanks to create a filtered map of uppercase keys and their values for numbers greater than 10.

Go
data := map[string]int{"a": 5, "b": 15, "c": 20}
result := map[string]int{
    [1]: [2],
}

for k, v := range data {
    if v [3] 10 {
        result[strings.ToUpper(k)] = v
    }
}
fmt.Println(result)
Drag options to blanks, or click blank then click option'
Ak
Bv
C>
Dstrings.ToUpper(k)
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase keys instead of uppercase.
Using wrong comparison operator or variable names.