Open mtchuyen opened 3 years ago
https://blog.canopas.com/golang-utility-functions-you-always-missed-ebeabae6b276
Ternary Operator được sử dụng bởi hai ký tự: ?
và :
Cú pháp sử dụng:
[condition (điều kiện)] ? statement1 : statement2
Ví dụ:
x = (y == 1) ? 20: 30;
được giải thích là: nếu y=1
thì x=20
, còn y != 1
thì x=30
var exp = 2;
var salary = exp < 1 ? 1000 :
exp < 2 ? 1500 :
exp < 3 ? 2000 : 3000
console.log(salary) //2000
the ternary operator known from languages like PHP
or JavaScript
is NOT available in Golang
.
The reason is a simple design choice. The operator although once understood, is an easy one is in fact a complicated construct for someone who is new to code. The Go programming language chose the simple approach of if-else. This is a longer version of the operator, but it is more readable.
Thực tế là nếu trong code của bạn có 1 đoạn cần xử lý như này: int value := a <= b ? a : b
thì bạn có thể viết như này trong Golang:
func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
The solution is obviously an if-else
block. It represents the same code in a much cleaner way
.
if {..} else {..}
Ví dụ:
test = function1(); if condition {test = function2()}
The map ternary is easy to read without parentheses:
c := map[bool]int{true: 1, false: 0} [5 > 4]
This response is not because:
if-else
chỉ cần duyệt 1 điều kiện)if/else
.Ví dụ như này (không đúng cấu trúc toán tử 3 ngôi nhưng đưa ra để thể hiện tốc độ tính toán)
func Ternary(statement bool, a, b interface{}) interface{} {
if statement {
return a
}
return b
}
func Abs(n int) int {
return Ternary(n >= 0, n, -n).(int)
}
This will not outperform if/else and requires cast but works. FYI: | Benchmark | num | ops |
---|---|---|---|
BenchmarkAbsTernary-8 | 100000000 | 18.8 ns/op | |
BenchmarkAbsIfElse-8 | 2000000000 | 0.27 ns/op |
Golang Magic: Modify Return Value Using Deferred Function