蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 Go 函数定义、多返回值、值传递与指针修改、高阶闭包及接收者方法

GO本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。explore_functions.go
explore_functions.go164 行
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"reflect"
	"runtime"
)

type CaseResult struct {
	Name     string `json:"name"`
	Summary  string `json:"summary"`
	Expected any    `json:"expected"`
	Actual   any    `json:"actual"`
	Passed   bool   `json:"passed"`
}

type LabOutput struct {
	Version string       `json:"version"`
	Cases   []CaseResult `json:"cases"`
}

func makeCase(name, summary string, expected, actual any) CaseResult {
	return CaseResult{
		Name:     name,
		Summary:  summary,
		Expected: expected,
		Actual:   actual,
		Passed:   reflect.DeepEqual(expected, actual),
	}
}

func maxInt(num1, num2 int) int {
	var result int
	if num1 > num2 {
		result = num1
	} else {
		result = num2
	}
	return result
}

func swapPair(x, y string) (string, string) {
	return y, x
}

func swapByValue(x, y int) {
	x, y = y, x
	_, _ = x, y
}

func swapByPointer(x, y *int) {
	*x, *y = *y, *x
}

func applyBinary(op func(int, int) int, a, b int) int {
	return op(a, b)
}

func makeCounter() func() int {
	i := 0
	return func() int {
		i++
		return i
	}
}

type Circle struct {
	radius float64
}

func (c Circle) getArea() float64 {
	return 3.14 * c.radius * c.radius
}

func main() {
	var cases []CaseResult

	// 1. func_definition_and_max
	arr := [3]int{10, 20, 30}
	cases = append(cases, makeCase(
		"func_definition_and_max",
		"验证自定义 max 函数调用与内置 len() 对字符串和数组的长度返回",
		map[string]any{
			"max_100_200": 200,
			"max_50_12":   50,
			"str_len":     5,
			"arr_len":     3,
		},
		map[string]any{
			"max_100_200": maxInt(100, 200),
			"max_50_12":   maxInt(50, 12),
			"str_len":     len("Hello"),
			"arr_len":     len(arr),
		},
	))

	// 2. multi_return_swap
	s1, s2 := swapPair("First", "Second")
	cases = append(cases, makeCase(
		"multi_return_swap",
		"验证 Go 函数返回多个值并由调用方同时接收",
		[]string{"Second", "First"},
		[]string{s1, s2},
	))

	// 3. pass_by_value_vs_pointer
	a, b := 100, 200
	swapByValue(a, b)
	afterVal := []int{a, b}
	swapByPointer(&a, &b)
	afterPtr := []int{a, b}
	cases = append(cases, makeCase(
		"pass_by_value_vs_pointer",
		"对比默认按值传递不影响实参与传指针地址修改调用方实参",
		map[string]any{
			"after_value_call":   []int{100, 200},
			"after_pointer_call": []int{200, 100},
		},
		map[string]any{
			"after_value_call":   afterVal,
			"after_pointer_call": afterPtr,
		},
	))

	// 4. func_as_value_and_closure
	sumVal := applyBinary(func(x, y int) int { return x + y }, 3, 4)
	next := makeCounter()
	seq := []int{next(), next(), next()}
	cases = append(cases, makeCase(
		"func_as_value_and_closure",
		"验证函数作为高阶函数实参传入以及匿名闭包捕获并保持递增状态",
		map[string]any{
			"apply_sum":   7,
			"closure_seq": []int{1, 2, 3},
		},
		map[string]any{
			"apply_sum":   sumVal,
			"closure_seq": seq,
		},
	))

	// 5. method_with_receiver
	c := Circle{radius: 10.0}
	cases = append(cases, makeCase(
		"method_with_receiver",
		"验证带接收者的结构体方法 Circle.getArea() 计算面积 314.0",
		314.0,
		c.getArea(),
	))

	out := LabOutput{
		Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
		Cases:   cases,
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(out); err != nil {
		panic(err)
	}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。

入口文件:projects/go-functions-lab/explore_functions.go

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore_functions.go,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Go

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip

下载课程关联工程包:Go

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1168.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习