我如何 return C 中的两种类型之一?
How do I return one of two types in C?
假设这段代码
typedef struct A {
...
} A;
typedef struct B {
...
} B;
// If it was TypeScript I would say `type uknown = A | B;`
uknown getAorB(int k) {
if (k > 0) return (A){...};
return (B){...};
}
根据参数 k
,函数 getAorB
应该 return A 或 B。好的,但是什么是 return 类型,是否可以在 C 中实现它?
一种方法是使用另一个包含 'type' 的结构
返回的结构。这可能是这样的:
#define STRUCTA 1
#define STRUCTB 2
typedef struct SUPER {
int type;
} SUPER;
typedef struct A {
int type;
...
} A;
typedef struct B {
int type;
...
} B;
SUPER* getAorB(int k) {
if (k > 0) {
A *a;
a = malloc(sizeof(*a));
a->type = STRUCTA;
return (SUPER*)a;
}
B *b;
b = malloc(sizeof(*b));
b->type = STRUCTB;
return (SUPER*)b;
}
然后在调用函数中检查 SUPER 的类型并将其转换为适当的函数。
A *a;
B *b;
if (returnedSuper->type == STRUCTA) {
a = (A*)returnedSuper;
}
else if (returnedSuper->type == STRUCTB) {
b = (B*)returnedSuper;
}
使用联合。
typedef struct A {
...
} A;
typedef struct B {
...
} B;
typedef union
{
struct A a;
struct B b;
}A_OR_B;
// If it was TypeScript I would say `type uknown = A | B;`
A_OR_B getAorB(int k) {
A_OR_B c;
if (k > 0) c.a.member = something;
else c.b.member = somethingelse;
return c;
}
假设这段代码
typedef struct A {
...
} A;
typedef struct B {
...
} B;
// If it was TypeScript I would say `type uknown = A | B;`
uknown getAorB(int k) {
if (k > 0) return (A){...};
return (B){...};
}
根据参数 k
,函数 getAorB
应该 return A 或 B。好的,但是什么是 return 类型,是否可以在 C 中实现它?
一种方法是使用另一个包含 'type' 的结构 返回的结构。这可能是这样的:
#define STRUCTA 1
#define STRUCTB 2
typedef struct SUPER {
int type;
} SUPER;
typedef struct A {
int type;
...
} A;
typedef struct B {
int type;
...
} B;
SUPER* getAorB(int k) {
if (k > 0) {
A *a;
a = malloc(sizeof(*a));
a->type = STRUCTA;
return (SUPER*)a;
}
B *b;
b = malloc(sizeof(*b));
b->type = STRUCTB;
return (SUPER*)b;
}
然后在调用函数中检查 SUPER 的类型并将其转换为适当的函数。
A *a;
B *b;
if (returnedSuper->type == STRUCTA) {
a = (A*)returnedSuper;
}
else if (returnedSuper->type == STRUCTB) {
b = (B*)returnedSuper;
}
使用联合。
typedef struct A {
...
} A;
typedef struct B {
...
} B;
typedef union
{
struct A a;
struct B b;
}A_OR_B;
// If it was TypeScript I would say `type uknown = A | B;`
A_OR_B getAorB(int k) {
A_OR_B c;
if (k > 0) c.a.member = something;
else c.b.member = somethingelse;
return c;
}