From the course: Learning Go

Use math operators - Go Tutorial

From the course: Learning Go

Use math operators

- [Instructor] Go supports the same set of mathematical operators that work in other C-style languages, including the usual math operators for addition, subtraction, multiplication, and division, and you also get all of the Bitwise operators that are available in C and Java. As I've mentioned previously, Go doesn't implicitly convert numeric types. So you can't take an integer value and, say, add it to a floating point value without conversion. In this code, I have one variable that's an integer and another one that's a float, and I try to add them together. This will result in an error, crashing the application, and I'll see the error message, invalid operation. To correctly add these values together, I have to convert one of the values to match the type of the other one. And you do this by wrapping the value in a function that has the same name as the target type. So now once again, I'm starting off with an integer and a float and I'm converting the integer to a float64 value before I add the two values together. And now the operation will be successful and I'll see the result. For mathematical operations that go beyond the capabilities of the simple math operators, look at the math package. This package has a whole bunch of functions and constants that you can use in your code, and here's one example. I'm starting with a floating value of 3.14159, then I'm rounding the value using the round function from the math package. This function rounds to the nearest integer. Then I'm out putting the result and here's what I'd see, the original value and the rounded value as a whole number. There are lots of these kinds of functions in the math package, and also a few constants. So for example, I could replace 3.14159 with the constant math.pi and that would work as well. I'll show you how to use these features of the math package in some hands-on coding in the next video.

Contents