Terminating blocks

March 29, 2024

Terminating statements

  1. 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/).

The rule today means that the block { fmt.Println("Wow, that was interesting!"); return; } is also a terminating statement.

Put another way, terminating statements still terminate, even if they’re wraped in an arbitrary number of other code blocks. return still terminates the function in this example, despite the extra, completely superflous code blocks:

func foo() {
	if somethingInterestingHappened() {
		{
			fmt.Println("Wow, that was interesting!")
			{
				return
			}
		}
	}

	fmt.Println("That was boring.")
}

Not really that profound, after all.

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


Terminating if statements

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 … 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.


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.


Terminating labeled statements

Today’s live stream is starting an hour later than usual. Join me at 16:00, CEST, for some live Go coding using TDD. Terminating statements … A labeled statement labeling a terminating statement. Labeled statement’s are not used a lot in Go. Terminating labeled statements even less so. But they do exist, just the same. Here’s an example, using goto, and a labeled terminating statement. func foo() { if someCondition { goto end } fmt.

Get daily content like this in your inbox!

Subscribe