2025-04-09 00:13:20 +08:00

40 lines
667 B
Go

package main
import "fmt"
// 基本函数定义
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
// 带返回值的函数
func add(a, b int) int {
return a + b
}
// 多返回值函数
func swap(x, y string) (string, string) {
return y, x
}
// 完成一个两个变量值互换的函数,使用泛型
func swapGeneric[T any](x, y T) (T, T) {
return y, x
}
func main() {
// 调用无返回值函数
greet("Gopher")
// 调用单返回值函数
sum := add(3, 5)
fmt.Println("3 + 5 =", sum)
// 调用多返回值函数
a, b := swap("hello", "world")
fmt.Println(a, b)
// 调用泛型函数
x, y := swapGeneric(1, 2)
fmt.Println(x, y)
}