How does this code operates?

It’s not clear how does this code calculates each individual number from the function argument:

for number != 0 {
	digit := number % 10
	number /= 10
	fmt.Printf("%d ", digit)
}

What does it mean number % 10?
And this number /= 10?

% is the modulus or remainder operator. The result is what’s left over as a remainder after division. Some examples:

10 % 7 = 3 (because 7x1 + 3 = 10)
5 % 2 = 1 (because 2x2 + 1 = 5)
23 % 7 = 2 (because 3x7 +2 = 23)

number % 10 is used to get the digit in the one’s place of number. Some examples:

38746 % 10 = 6
8349 % 10 = 9
23 % 10 = 3

To answer your second question,

number /= 10

is short for

number = number / 10

(They are almost identical, but not quite because in the second case, if number is an expression it’s evaluated twice.)

2 Likes

Careful there, those are not interchangeable. In Go % is actually the remainder operation, not the modulus operation. So in Go both 5 % 4 and 5 % -4 give you 1 as the result, while if you try in Google with 5 modulo (4) and 5 modulo (-4), you’ll get 1 and -3 as you’d expect with the modulus operation.

3 Likes

Hi Ignacio,

Thanks for the correction on that! I should have written just “remainder” and not “modulus”.

You raised a very good point because different programming languages implement the remainder operator (which may be called modulus or modulo in other languages) in different ways. Just now I’m reading this Wikipedia article


and I realized I’ve been getting away with something for a long time because Go’s remainder operator works the same way as in all of JavaScript, Bash and C (ISO 1999 standard) that I’m used to programming in.

With Go’s increasing popularity, especially for web development and cloud computing, many existing apps are being rewritten in Go. So this is an important detail to be aware of when moving to Go from some other programming language.

3 Likes

That’s right, there are differences on how languages treat and even name these operations, though many that follow the C convention tend to make it clear that they are taking the remainder when using % and even call it the remainder operation. Other languages explicitly offer the rem and mod functions/methods to be clear about the difference. Still, there’s controversy and confusion. But names apart, I think we agree that what’s really important is to know what the language in use is doing so you don’t get bitten by it, for example when porting code.

Here’s a very simple article that touches the issue and has some interesting links to other sources.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.