0
0
Goprogramming~20 mins

Why packages are used in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Package Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use packages in Go?

Which of the following is the main reason Go uses packages?

ATo organize code into reusable and manageable units
BTo allow multiple main functions in one program
CTo make the program run faster by compiling packages separately
DTo avoid writing comments in the code
Attempts:
2 left
💡 Hint

Think about how grouping code helps in big projects.

Predict Output
intermediate
2:00remaining
Output of package usage example

What will be the output of this Go program?

Go
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Sqrt(16))
}
AError: undefined function Sqrt
B16
C4
D0
Attempts:
2 left
💡 Hint

Look at what math.Sqrt does.

Predict Output
advanced
2:00remaining
What error occurs without importing package?

What error will this Go code produce?

Go
package main

func main() {
	println("Hello, world!")
	fmt.Println("Hello again!")
}
Aruntime error: nil pointer dereference
Bprints Hello, world! and Hello again!
Ccompile error: missing main function
Dcompile error: undefined: fmt
Attempts:
2 left
💡 Hint

Check if the fmt package is imported.

🧠 Conceptual
advanced
2:00remaining
Benefits of using packages in Go

Which of these is NOT a benefit of using packages in Go?

AAutomatically increases program execution speed
BAllows code reuse across different programs
CImproves code readability and maintenance
DHelps avoid name conflicts by using package namespaces
Attempts:
2 left
💡 Hint

Think about what packages do and do not do.

🚀 Application
expert
3:00remaining
How to create and use a custom package in Go

You want to create a package named greetings with a function Hello that returns "Hello, Go!". Which code snippet correctly defines and uses this package?

A
package main

func Hello() string {
	return "Hello, Go!"
}

func main() {
	fmt.Println(Hello())
}
B
package greetings

func Hello() string {
	return "Hello, Go!"
}

// In main.go
package main

import (
	"fmt"
	"greetings"
)

func main() {
	fmt.Println(greetings.Hello())
}
C
package greetings

func Hello() {
	fmt.Println("Hello, Go!")
}

// In main.go
package main

func main() {
	greetings.Hello()
}
D
package greetings

func Hello() string {
	return "Hello, Go!"
}

func main() {
	fmt.Println(Hello())
}
Attempts:
2 left
💡 Hint

Remember packages need to be imported and functions called with package name.