Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加 IfThenElse 函数返回泛型结果 #259

Merged
merged 4 commits into from
Nov 9, 2024

Conversation

bigdavidwong
Copy link
Contributor

添加 IfThenElse 函数

此 PR 添加了一个 IfThenElse 函数,它根据条件返回对应的泛型结果。该函数允许在单行代码中实现类似三元运算符的功能。

功能概述:

  • IfThenElse[T any](condition bool, trueValue, falseValue T) T 根据布尔条件返回 trueValuefalseValue
  • 支持泛型,能够处理任意类型的输入。
  • 请注意,trueValuefalseValue 在传入时即会访问,因此调用方需确保它们的合法性。

示例:

result := IfThenElse(true, "Success", "Failure")
fmt.Println(result) // 输出: Success

@flycash
Copy link
Contributor

flycash commented Nov 2, 2024

我会觉得说,可能需要的是一个类似三木操作符的东西,解决我长期以来的一个困扰:
if xxx
doSomething
else
doSomething

然后还要考虑获得返回值的问题

@flycash
Copy link
Contributor

flycash commented Nov 2, 2024

或者提供两个方法:
IfThenElse 和 IfThenElseFunc

一个是用来计算值,一个是用来执行动作

condition.go Outdated Show resolved Hide resolved
@bigdavidwong
Copy link
Contributor Author

@flycash 已按照建议进行了修改,请帮忙重新审查,谢谢~

condition.go Outdated Show resolved Hide resolved
Copy link
Contributor

@flycash flycash left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rebase 一下最新代码。

huangdawei and others added 4 commits November 7, 2024 16:47
1. 增加了一个条件判断返回泛型结果的函数;
1. 增加了一个条件判断执行对应方法的函数;
2. 调整和增加单元测试和Example;
@flycash flycash merged commit 19c740e into ecodeclub:dev Nov 9, 2024
4 checks passed
@flycash
Copy link
Contributor

flycash commented Nov 9, 2024

非常感谢

flycash pushed a commit that referenced this pull request Nov 12, 2024
* update
1. 增加了一个条件判断返回泛型结果的函数;
1. 增加了一个条件判断执行对应方法的函数;
2. 调整和增加单元测试和Example;

* IfThenElseFunc固定增加错误返回,泛型T作为用户可以自定义返回的结果

---------

Co-authored-by: huangdawei <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants