76 lines
2.2 KiB
Python
76 lines
2.2 KiB
Python
import sys
|
||
import os
|
||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "python"))
|
||
|
||
from gobridge import gobridge, run
|
||
from typing import Iterator
|
||
|
||
|
||
@gobridge
|
||
def add(a: int, b: int) -> int:
|
||
return a + b
|
||
|
||
|
||
@gobridge
|
||
def range_gen(start: int, stop: int) -> Iterator[int]:
|
||
"""流式输出:对应 Go 侧 Invoke[chan int]"""
|
||
for i in range(start, stop):
|
||
yield i
|
||
|
||
|
||
@gobridge
|
||
def sum_stream(numbers: Iterator[int]) -> int:
|
||
"""流式输入:对应 Go 侧传入 chan int 参数"""
|
||
return sum(numbers)
|
||
|
||
|
||
@gobridge
|
||
def double_stream(numbers: Iterator[int]) -> Iterator[int]:
|
||
"""双向流:输入每个数,yield 其平方,对应 Go 侧 Invoke[chan int](c, ctx, "double_stream", inputChan)"""
|
||
for n in numbers:
|
||
yield n * n
|
||
|
||
|
||
# ── struct(dict)类型 ──────────────────────────────────────────────────────
|
||
|
||
@gobridge
|
||
def get_user(uid: int) -> dict:
|
||
"""普通调用:返回一个 struct(Go 对应 User)"""
|
||
return {"id": uid, "name": f"user_{uid}", "score": uid * 1.5}
|
||
|
||
|
||
@gobridge
|
||
def total_score(users: list) -> float:
|
||
"""slice 输入:接收 []User,返回总分"""
|
||
return sum(u["score"] for u in users)
|
||
|
||
|
||
@gobridge
|
||
def enrich_users(users: list) -> list:
|
||
"""slice 输入输出:为每个 user 追加 level 字段"""
|
||
result = []
|
||
for u in users:
|
||
u = dict(u)
|
||
u["level"] = "gold" if u["score"] >= 10 else "silver"
|
||
result.append(u)
|
||
return result
|
||
|
||
|
||
# ── struct/slice 流式组合 ────────────────────────────────────────────────────
|
||
|
||
@gobridge
|
||
def gen_users(count: int) -> Iterator[dict]:
|
||
"""流式输出 struct:yield 多个 User,对应 Go 侧 Invoke[chan User]"""
|
||
for i in range(1, count + 1):
|
||
yield {"id": i, "name": f"user_{i}", "score": float(i * 3)}
|
||
|
||
|
||
@gobridge
|
||
def process_users(users: Iterator[dict]) -> Iterator[dict]:
|
||
"""双向流 struct:输入流式 User,yield 处理后的 User"""
|
||
for u in users:
|
||
yield {"id": u["id"], "name": u["name"].upper(), "score": u["score"] * 2}
|
||
|
||
|
||
run()
|