So far, our functions have only performed actions like printing to the console. But functions can also calculate values and return them back to the caller, making them even more powerful.
To return a value from a function, you need to:
return keyword followed by the value to returnfunc double(n int) int {
return n * 2
}
func main() {
result := double(5)
fmt.Println(result) // Output: 10
}
The int after the parameters means this function returns an integer value.
The return type can be any valid Go type:
// Returns a string
func greet(name string) string {
return "Hello, " + name
}
// Returns a boolean
func isStrongEnough(power int) bool {
return power > 9000
}
// Returns a float
func calculateMultiplier(level int) float64 {
return float64(level) * 1.5
}
Once a function returns a value, you can use it like any other value:
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(10, 20)
fmt.Println("Sum:", sum) // Output: Sum: 30
// Use directly in expressions
total := add(5, 10) + add(3, 7)
fmt.Println("Total:", total) // Output: Total: 25
// Use in conditionals
if add
When a return statement is executed, the function immediately exits. Any code after return will not run:
func checkValue(n int) int {
if n < 0 {
return 0 // Exit early for negative numbers
}
fmt.Println("Processing:", n)
return n * 2
}
func main() {
fmt.Println(checkValue(-5)) // Returns 0, doesn't print "Processing"
fmt.Println(checkValue(10)) // Prints "Processing: 10", returns 20
}
If your function has a return type, every possible code path must return a value:
// This will cause a compiler error!
func badFunction(n int) int {
if n > 0 {
return n * 2
}
// Error: missing return for when n <= 0
}
// This is correct
func goodFunction(n int) int {
if n > 0 {
return n * 2
}
return 0 // Handle all cases
}
func kaioken(basePower int) int {
return basePower * 5
}
func main() {
gokuPower := 9001
fmt.Println("Base power:", gokuPower)
boostedPower := kaioken(gokuPower)
fmt.Println("After Kaioken:", boostedPower)
}
// Output:
// Base power: 9001
// After Kaioken: 45005
You can create complex calculations by combining parameters and return values:
func calculateDamage(attackPower int, defense int) int {
damage := attackPower - defense
if damage < 0 {
return 0
}
return damage
}
func main() {
damage := calculateDamage(150, 50)
fmt.Println("Damage dealt:", damage) // Output: Damage dealt: 100
blocked := calculateDamage(30, 100)
fmt.Println("Damage dealt:", blocked) // Output: Damage dealt: 0
For this challenge, create a function called fusionBoost that accepts two parameters: powerLevel1 (int) and powerLevel2 (int).
The function should:
intThen in your main function:
fusionBoost with power levels 5000 and 7000fusedPower"Fused power level: [fusedPower]"Expected output:
Fused power level: 120000