原文来源于:https://www.yii666.com/blog/39486.html

原标题:golang三元表达式 原创

golang并没有像C语言一样提供三元表达式。三元表达式的好处是可以用一行代码解决原本需要多行代码才能完成的功能,让冗长的代码瞬间变得简洁。不过对于新手来说,建议还是少用三元表达式。在这里,我用golang通过函数的方式实现了三元表达式。网址:yii666.com<

package magic
/*
实现三元表达式的功能
 */
func If(condition bool, trueVal, falseVal interface{}) interface{} {
	if condition {
		return trueVal
	} else {
		return falseVal
	}
}
package magic
/*
单元测试案例
*/
import (
	"testing"
)

func TestIf(t *testing.T) {
	var a, b int = 2, 3
	res := If(a > b, a, b)
	if res == a {
		t.Error("三元表达式计算错误")
	}
	t.Log(res)
}

执行结果文章来源地址https://www.yii666.com/blog/39486.html网址:yii666.com文章来源地址:https://www.yii666.com/blog/39486.html

文章地址https://www.yii666.com/blog/39486.html