通过编译时字符串,调用到某实例的方法 #232
jiacai2050
started this conversation in
General
Replies: 1 comment
-
加一个可以有返回值, 在线运行 const std = @import("std");
const MyStruct = struct {
value: i32,
pub fn print(self: *const MyStruct) void {
std.debug.print("Value: {}\n", .{self.value});
}
pub fn add(self: *MyStruct, num: i32) i32 {
self.value += num;
return self.value;
}
};
fn callMethod(comptime T: type, obj: anytype, comptime method: []const u8, args: anytype) T {
const ObjType = @TypeOf(obj);
const obj_type_info = @typeInfo(ObjType);
const is_pointer, const ActualType = blk: {
switch (obj_type_info) {
.pointer => break :blk .{ true, obj_type_info.pointer.child },
else => break :blk .{ false, ObjType },
}
};
if (!@hasDecl(ActualType, method)) {
@compileError("Method '" ++ method ++ "' not found in type '" ++ @typeName(ObjType) ++ "'");
}
const ptr = if (is_pointer) obj else &obj;
const func = @field(ActualType, method);
return @call(.auto, func, .{ptr} ++ args);
}
pub fn main() void {
var obj = MyStruct{ .value = 10 };
// with return value
const result = callMethod(i32, &obj, "add", .{5});
std.debug.print("Result of add: {}\n", .{result});
// without return value
callMethod(void, obj, "print", .{});
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Beta Was this translation helpful? Give feedback.
All reactions