#Returning a union value in a function?

1 messages · Page 1 of 1 (latest)

dry elbow
#

Why does this work:

const value = getValue(bool);

//def
fn getValue(comptime T: type) T {
    switch (@typeInfo(T)) {
        .bool => return true,
        .int => return 4,
        else => return null,
    }
}```

but this doesn't

```c
const myUnion = MyUnion{ .bool = true }

const value = getUnionValue(bool, myUnion);

//def
const MyUnion = union(enum) {
    bool: bool,
    int: i32,
};

fn getUnionValue(comptime T: type, myUnion: MyUnion) T {
    switch (myUnion) {
        .bool => return true,
        .int => return 4,
    }
}```

The compiler yells at me for having a possible return that's not a bool with the union, but it has no problems with non bool returns when just using a type.
naive venture
#

in getValue, T is known at comptime so it only has to analyze the one branch

#

what do you expect getUnionValue to do if you call it as getUnionValue(bool, .{.int = 4})?

dry elbow
#

ah, interesting.

what do you expect getUnionValue to do if you call it as getUnionValue(bool, .{.int = 4})?

That's when I would expect to get a compiler error.

I came across the issue when working with some of the JSON tools.

A common pattern I see

const value = try std.json.parseFromSlice(std.json.Value, allocator, jsonString, .{});

const item = value.object.get("key").?.bool;```

That last line doesn't seem much different functionally than say a wrapper like:
```c
const item = value.get(bool, "key");```

So it didn't hurt me too much to write.