Terminating if statements

April 2, 2024

Last week we saw that a block that ends in a terminaging statement is itself a terminating statement.

Today we expand a bit on that idea:

Terminating statements

  1. An “if” statement in which:

    • the “else” branch is present, and
    • both branches are terminating statements.

In other words, the following counts as a terminating statement:

if somethingInterestingHappened() {
	fmt.Println("Wow, that was interesting!")
	return
} else {
	fmt.Println("That was boring.")
	return
}

Both branches of the if statement terminate, so the statement as a whole is a terminating statement. Put another way: There’s no possible way any code following this block would be executed, therefore it is terminating.

What would make this not-terminating?

  1. Obviously, if we remove either return statement
  2. If the else were replaced with an else if
  3. If we add some statement to either block that breaks out of otherwise normal flow control (such as a goto, continue, or break—assuming, of course, this code is part of a relevant loop or select statement.)

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


If statements

Today I’ll be live coding again. I hope you can join, and ask your Go-related questions as I continue to hack away on my open-source project, using TDD. Catch the stream on YouTube. Have you ever tried to explain an “if” statement in as few words as possible? It’s such a simple concept, that I don’t think I’ve ever bothered trying to explain it. Well, today’s section of the Go spec does explain it.


Terminating blocks

Terminating statements … A block in which the statement list ends in a terminating statement. What exactly does this mean? It means that if you have an (explicit) code block that ends in a terminating statement, the block itself is considered a terminating statement. Confused? How about an example: func foo() { if somethingInterestingHappened() { fmt.Println("Wow, that was interesting!") return } fmt.Println("That was boring.") } In this example, return is a terminating statement, as we saw [two days ago](/ archive/2024-03-27-terminating-statements/).


Terminating statements conclusion

So we’ve made it through the list of 8 types of terminating statements. We conclude this section with a couple additional comments: Terminating statements … All other statements are not terminating. A statement list ends in a terminating statement if the list is not empty and its final non-empty statement is terminating. What is a statement list? It’s, well, eh… a list of statements! It’s not as interesting or profound as it sounds.

Get daily content like this in your inbox!

Subscribe