golang三元表達式

golang並沒有像C語言一樣提供三元表達式。三元表達式的好處是可以用一行代碼解決原本需要多行代碼才能完成的功能,讓冗長的代碼瞬間變得簡潔。不過對於新手來說,建議還是少用三元表達式。在這裡,我用golang通過函數的方式實現了三元表達式。

<code>package magic
/*
實現三元表達式的功能
 */
func If(condition bool, trueVal, falseVal interface{}) interface{} {
	if condition {
		return trueVal
	} else {
		return falseVal
	}
}/<code>
<code>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)
}

/<code>

執行結果


golang三元表達式


分享到:


相關文章: