我在代碼中的不同版本中有很多次:
func f() (bool, bool) {
value, successFulOperation := someStuff()
return value, successFulOperation
}
// somewhere else
value, successfulOperation := f()
if value && successfulOperation {
// do stuff
}
// do stuff僅當value為真且檢索到的操作value成功且無錯誤時才應執行。換句話說:我不在乎valueor successfulOperation。我只關心value && successfulOperation。
我想避免的解決方案(似乎很冗長):
value, successfulOperation := f()
actualValue := value && successfulOperation
if actualValue {...}
上面的代碼確實簡化了。實際上, if 條件將被嵌套并且更加復雜。
我想要的是:
一個包裝器f將兩個值合二為一。我怎么做?該解決方案應該適用于任何采用任何引數并回傳兩個布林值的函式。
以下不起作用:
type doubleBoolFunc func(...interface{}) (bool, bool)
func and(fn doubleBoolFunc, params ...interface{}) bool {
b1, b2 := fn(params...)
return b1 && b2
}
actualValue := and(f())
uj5u.com熱心網友回復:
在 go 1.18 1中的語言中使用泛型之前,您無法撰寫包裝函式來將兩個 bool 轉換為一個。或者至少你可以,使用反射,但它是一團糟。
但是你可以用 go 1.17 寫這個:
func both(x, y bool) bool {
return x && y
}
func f() (bool, bool) {
return true, false
}
func main() {
r := both(f())
fmt.Println(r)
}
但更實用的(在我看來)是避免這種并發癥,并使用 1 行 if。并非一切都需要成為一個函式或抽象掉:
if a, b := f(); a && b {
...
}
[1]即使在 go 1.18 中引入了泛型,我也不認為有一種方法可以指定一個泛型型別,該型別表示具有任意引數并回傳兩個 bool 的函式。
uj5u.com熱心網友回復:
func and(a, b bool) bool {
return a && b
}
那么如果 f 回傳 2 bool
value := and(f())
將作業
uj5u.com熱心網友回復:
要修復問題末尾的代碼,請不要呼叫 function f(),只需參考函式名稱f,然后列出其引數:
// actualValue := and(f(args...))
actualValue := and(f, args...)
https://go.dev/play/p/KAT2L58ZQy3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400782.html
