You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zig语言中如何从函数返回另一个函数?现有实现是否有更优方案?

优化Zig泛型函数返回函数指针的实现

你的实现可以简化很多,不需要借助结构体来包裹函数,Zig允许在函数内部直接定义嵌套函数,并且可以直接返回其指针。

简化版实现

const std = @import("std");

fn DefaultCompareFn(T: type) *const fn(T, T) i8 {
    fn defaultCompareFn(value1: T, value2: T) i8 {
        if (value1 > value2) {
            return 1;
        } else if (value1 < value2) {
            return -1;
        }
        return 0;
    }
    return &defaultCompareFn;
}

test "Fn" {
    const func = DefaultCompareFn(i8);
    try std.testing.expect(func(5, 6) == -1);
    try std.testing.expect(func(6, 5) == 1);
    try std.testing.expect(func(5, 5) == 0);
}

进一步优化:复用标准库实现

你的比较逻辑和Zig标准库中的std.math.order完全一致,它会返回std.math.Order枚举,我们可以将其转换为i8直接复用,避免重复造轮子:

const std = @import("std");
const Order = std.math.Order;

fn DefaultCompareFn(T: type) *const fn(T, T) i8 {
    fn compare(a: T, b: T) i8 {
        return switch (std.math.order(a, b)) {
            .gt => 1,
            .lt => -1,
            .eq => 0,
        };
    }
    return &compare;
}

test "Fn" {
    const func = DefaultCompareFn(i8);
    try std.testing.expect(func(5, 6) == -1);
    try std.testing.expect(func(6, 5) == 1);
    try std.testing.expect(func(5, 5) == 0);
}

优化说明

  1. 移除了不必要的结构体包裹:原来的DC结构体没有实际作用,直接返回嵌套函数的指针即可,每个DefaultCompareFn(T)的实例化都会生成对应的专属比较函数实现。
  2. 简化了代码结构:减少了冗余的结构体定义和实例化步骤,逻辑更直观。
  3. 复用标准库逻辑:std.math.order已经处理了所有可比较类型的大小判断,使用它能保证逻辑的正确性和一致性。

内容的提问来源于stack exchange,提问作者Jaime Lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 06:42:46