How to replace the ternary operator from C/C++ in Go? Idiomatic ways
Hello everyone! I just started learning Go after several years of working with C++ and ran into a problem. In C++, I often used the ternary operator for short conditional assignments, for example:
```cpp
int min = (a < b) ? a : b;
```
But Go doesn't have such an operator. I understand that you can use a regular if/else:
```go
var min int
if a < b {
min = a
} else {
min = b
}
```
But this takes 4-5 lines instead of one. For simple things like choosing a value or formatting a string, this seems too verbose. For example, I want to do something like:
```go
fmt.Println("Result: " + (score > 50 ? "Pass" : "Fail"))
```
Or assign a value depending on a condition inside a return:
```go
return (isValid ? data : defaultValue)
```
How should this be done correctly in Go?
No answers yet.
Log in to leave an answer