Functions allow you to organize your code into reusable blocks that can be called multiple times. They're essential for avoiding repetition and making your code more maintainable.
To create a function in Go, you use the func keyword, followed by the function name, parameters in parentheses, and the function body in curly braces:
func greet() {
fmt.Println("Hello!")
}
This simple function takes no parameters and prints "Hello!" when called.
Once you've defined a function, you can call it by using its name followed by parentheses:
func greet() {
fmt.Println("Hello!")
}
func main() {
greet() // Calls the function
greet() // You can call it multiple times
}
// Output:
// Hello!
// Hello!
Functions become much more powerful when they accept parameters. Parameters allow you to pass data into the function:
func greet(name string) {
fmt.Println("Hello,", name)
}
func main() {
greet("Goku") // Output: Hello, Goku
greet("Vegeta") // Output: Hello, Vegeta
}
The parameter name string means the function expects a string value to be passed in when called.
Imagine you need to check if multiple characters' power levels are over 9000:
// Without functions - repetitive!
if goku.PowerLevel > 9000 {
fmt.Println("It's over 9000!")
}
if vegeta.PowerLevel > 9000 {
fmt.Println("It's over 9000!")
}
if gohan.PowerLevel > 9000 {
fmt.Println("It's over 9000!")
}
This is tedious and error-prone. With a function:
func checkPowerLevel(powerLevel int) {
if powerLevel > 9000 {
fmt.Println("It's over 9000!")
}
}
func main() {
checkPowerLevel(goku.PowerLevel)
checkPowerLevel(vegeta.PowerLevel)
checkPowerLevel(gohan.PowerLevel)
}
Much cleaner! The logic is written once and reused three times.
Parameters must have a type specified. This tells Go what kind of data the function expects:
func printNumber(n int) {
fmt.Println("Number:", n)
}
func printName(name string) {
fmt.Println("Name:", name)
}
func printActive(isActive bool) {
fmt.Println("Active:", isActive)
}
For this challenge, create a function called transformationBoost that accepts a parameter basePower (an int).
The function should:
basePower is greater than or equal to 5000"Transformation unlocked!""Not strong enough yet"Then in your main function, call transformationBoost three times with these values: 4500, 5000, and 7000.
The function signature should be:
func transformationBoost(basePower int) {
// Your code here
}
Expected output:
Not strong enough yet
Transformation unlocked!
Transformation unlocked!