forked from steger/pr3-sose2026
49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
// Functions are defined with the func keyword, followed by the function name,
|
|
// a list of parameters in parentheses, and the return type.
|
|
func plus(a int, b int) int {
|
|
return a + b
|
|
}
|
|
|
|
// Function overloading is not supported in Go, but we can achieve similar functionality
|
|
// by using different function names or by using variadic functions.
|
|
// func plus(a float64, b float64) float64 { // compile error: function plus redeclared in this block
|
|
// return a + b
|
|
// }
|
|
|
|
// A function with multiple parameters of the same type can be shortened by listing the type only once.
|
|
func plusPlus(a, b, c int) int {
|
|
return a + b + c
|
|
}
|
|
|
|
// Named return values are treated as variables defined at the top of the function.
|
|
// A return statement without arguments returns the current values of the named return variables.
|
|
func plusNamed(a, b int) (result int) {
|
|
result = a + b
|
|
return
|
|
}
|
|
|
|
// A function can return multiple values. Here we return the sum and a formatted string description of the operation.
|
|
func plusDescription(a int, b int) (int, string) {
|
|
result := a + b
|
|
return result, fmt.Sprintf("%d+%d = %d", a, b, result)
|
|
}
|
|
|
|
func main() {
|
|
|
|
res := plus(1, 2)
|
|
fmt.Println("1+2 =", res)
|
|
|
|
res = plusPlus(1, 2, 3)
|
|
fmt.Println("1+2+3 =", res)
|
|
|
|
res = plusNamed(1, 2)
|
|
fmt.Println("1+2 =", res)
|
|
|
|
_, desc := plusDescription(1, 2)
|
|
fmt.Println(desc)
|
|
}
|