Nice programing

한 줄짜리 if else 문을 수행하는 방법은 무엇입니까?

nicepro 2020. 10. 18. 19:32
반응형

한 줄짜리 if else 문을 수행하는 방법은 무엇입니까?


PHP에서하는 것처럼 go (golang)에서 변수 할당을 사용하여 간단한 if-else 문을 작성할 수 있습니까?

$var = ( $a > $b )? $a: $b;

현재 다음을 사용해야합니다.

var c int
if a > b {
    c = a
} else {
    c = b
}

이 제어문이 있으면 이름이 기억 나지 않아서 사이트 내 및 Google 검색을 통해 정보를 찾을 수 없습니다. : /


언급했듯이 Go는 삼진 1 라이너를 지원하지 않습니다. 내가 생각할 수있는 가장 짧은 형식은 다음과 같습니다.

var c int
if c = b; a > b {
    c = a
}

나는 종종 다음을 사용합니다.

c := b
if a > b {
    c = a
}

기본적으로 @Not_a_Golfer와 동일하지만 유형 추론을 사용 합니다 .


다른 사람들이 언급 Go했듯이은 삼항 원 라이너를 지원하지 않습니다. 그러나 원하는 것을 달성하는 데 도움이되는 유틸리티 함수를 작성했습니다.

// IfThenElse evaluates a condition, if true returns the first parameter otherwise the second
func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
    if condition {
        return a
    }
    return b
}

다음은 사용 방법을 보여주는 몇 가지 테스트 사례입니다.

func TestIfThenElse(t *testing.T) {
    assert.Equal(t, IfThenElse(1 == 1, "Yes", false), "Yes")
    assert.Equal(t, IfThenElse(1 != 1, nil, 1), 1)
    assert.Equal(t, IfThenElse(1 < 2, nil, "No"), nil)
}

재미를 위해 다음과 같은 더 유용한 유틸리티 함수를 작성했습니다.

IfThen(1 == 1, "Yes") // "Yes"
IfThen(1 != 1, "Woo") // nil
IfThen(1 < 2, "Less") // "Less"

IfThenElse(1 == 1, "Yes", false) // "Yes"
IfThenElse(1 != 1, nil, 1)       // 1
IfThenElse(1 < 2, nil, "No")     // nil

DefaultIfNil(nil, nil)  // nil
DefaultIfNil(nil, "")   // ""
DefaultIfNil("A", "B")  // "A"
DefaultIfNil(true, "B") // true
DefaultIfNil(1, false)  // 1

FirstNonNil(nil, nil)                // nil
FirstNonNil(nil, "")                 // ""
FirstNonNil("A", "B")                // "A"
FirstNonNil(true, "B")               // true
FirstNonNil(1, false)                // 1
FirstNonNil(nil, nil, nil, 10)       // 10
FirstNonNil(nil, nil, nil, nil, nil) // nil
FirstNonNil()                        // nil

이들 중 하나를 사용하려면 https://github.com/shomali11/util에서 찾을 수 있습니다.


정답을 알려 주셔서 감사합니다.

방금 Golang FAQ (duh)를 확인 했는데 다음과 같은 언어로 제공되지 않는다고 분명히 명시되어 있습니다.

Go에? : 연산자가 있습니까?

Go에는 삼항 형식이 없습니다. 다음을 사용하여 동일한 결과를 얻을 수 있습니다.

if expr {
    n = trueVal
} else {
    n = falseVal
}

주제에 관심이있을 수있는 추가 정보 :


한 가지 가능한 방법이 있는지 제가 확인하고지도, 간단한 사용하여 하나 개의 라인에서이 작업을 수행하려면 a > b이 경우 true내가 할당하고 ca, 그렇지 않은b

c := map[bool]int{true: a, false: b}[a > b]

그러나 이것은 놀랍게 보이지만 경우에 따라 평가 순서 때문에 완벽한 솔루션이 아닐 수도 있습니다. 예를 들어, 나는 객체가되어 있는지 여부를 확인하고 경우에 nil, 그것의 다음 코드에서 모습을 몇 가지 속성을 얻을 수있는 것이다 panic의 경우myObj equals nil

type MyStruct struct {
   field1 string
   field2 string 
}

var myObj *MyStruct
myObj = nil 

myField := map[bool]string{true: myObj.field1, false: "empty!"}[myObj != nil}

조건을 평가하기 전에 맵이 먼저 생성되고 빌드 myObj = nil되므로이 경우 단순히 패닉 상태가됩니다.

단 한 줄로도 조건을 수행 할 수 있다는 점을 잊지 말고 다음을 확인하십시오.

var c int
...
if a > b { c = a } else { c = b}

때로는 익명 함수를 사용하여 동일한 줄에서 정의 및 할당을 수행하려고합니다. 아래와 같이 :

a, b = 4, 8

c := func() int {
    if a >b {
      return a
    } 
    return b
  } ()

https://play.golang.org/p/rMjqytMYeQ0


매우 유사한 구조가 언어로 제공됩니다.

**if <statement>; <evaluation> {
   [statements ...]
} else {
   [statements ...]
}*

*

if path,err := os.Executable(); err != nil {
   log.Println(err)
} else {
   log.Println(path)
}

이를 위해 클로저를 사용할 수 있습니다.

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, func() { dothis() }, func() { dothat() })
}

The only gripe I have with the closure syntax in Go is there is no alias for the default zero parameter zero return function, then it would be much nicer (think like how you declare map, array and slice literals with just a type name).

Or even the shorter version, as a commenter just suggested:

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, dothis, dothat)
}

You would still need to use a closure if you needed to give parameters to the functions. This could be obviated in the case of passing methods rather than just functions I think, where the parameters are the struct associated with the methods.


Use lambda function instead of ternary operator

Example 1

to give the max int

package main

func main() {

    println( func(a,b int) int {if a>b {return a} else {return b} }(1,2) )
}

Example 2

Suppose you have this must(err error) function to handle errors and you want to use it when a condition isn't fulfilled. (enjoy at https://play.golang.com/p/COXyo0qIslP)

package main

import (
    "errors"
    "log"
    "os"
)

// must is a little helper to handle errors. If passed error != nil, it simply panics.
func must(err error) {
    if err != nil {
        log.Println(err)
        panic(err)
    }
}

func main() {

    tmpDir := os.TempDir()
    // Make sure os.TempDir didn't return empty string
    // reusing my favourite `must` helper
    // Isn't that kinda creepy now though?
    must(func() error {
        var err error
        if len(tmpDir) > 0 {
            err = nil
        } else {
            err = errors.New("os.TempDir is empty")
        }
        return err
    }()) // Don't forget that empty parentheses to invoke the lambda.
    println("We happy with", tmpDir)
}

참고URL : https://stackoverflow.com/questions/26545883/how-to-do-one-liner-if-else-statement

반응형