Search code examples
gocompiler-constructionlanguage-design

Difference between if as an expression and if as a statement


So I was watching this video on the Go language - https://www.youtube.com/watch?v=p9VUCp98ay4 , and at around 6:50 a guy asks a question about why they implemented if's as statements and not expressions. What is the difference between those two implementations? As far as I know, I've never had to change the way I use a conditional based on the language.

Edit: and what does he mean that "you need values rather than variables" in his question?


Solution

  • The difference between expressions and statements is that expressions produce a value and thus can be used in places where values are required. So expressions can be used as values for variables, arguments to functions or operands to operators. Statements can't.

    and what does he mean that "you need values rather than variables" in his question?

    I assume that by vals he means constants (which are called vals in Scala for example).

    If if were an expression, you could do this:

    const myValue = if condition { value1 } else { value2 }
    

    Since if is not an expression, you have to do this:

    var myValue
    if condition {
        myValue = value1
    } else {
        myValue = value2
    }
    

    So you needed to make your variable mutable (use var instead of const), which is what the person asking the question likely meant.