How to Add Two Numbers in Go
Created
Modified
Integers And Floating Point Numbers
Go has several different types to represent numbers. Generally we split numbers into two different kinds: integers and floating-point numbers.
Make a main.go file containing the following:
package main
import "fmt"
func main() {
fmt.Println("1 + 2 =", 1+2)
// a floating point number
fmt.Println("1 + 2 =", 1.0+2.0)
}
$ go run main.go 1 + 2 = 3 1 + 2 = 3
In addition to addition Go has several other operators:
package main
import "fmt"
func main() {
fmt.Println("5 + 3 =", 5+3)
// subtraction
fmt.Println("5 - 3 =", 5-3)
// multiplication
fmt.Println("5 * 3 =", 5*3)
// division
fmt.Println("5 / 3 =", 5/3)
// remainder
fmt.Println("5 % 3 =", 5%3)
}
$ go run main.go 5 + 3 = 8 5 - 3 = 2 5 * 3 = 15 5 / 3 = 1 5 % 3 = 2
Golang max int
To get the maximum value of the int64 type, use math.MaxInt64 constant.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("int64 max:", math.MaxInt64)
// based on the platform you are executing
maxInt := int(^uint(0) >> 1)
fmt.Println("int max:", maxInt)
}
$ go run main.go int64 max: 9223372036854775807 int max: 9223372036854775807