Go Number Type Fundamentals
Go is a statically typed programming language, which means that variables must be declared with a specific data type. In Go, there are several number types that can be used to represent different types of numerical values. Understanding the fundamentals of these number types is crucial for writing efficient and correct Go code.
Go Integer Types
Go provides several integer types, including int8
, int16
, int32
, int64
, uint8
, uint16
, uint32
, and uint64
. The int
and uint
types are also available, which are platform-dependent and can be either 32-bit or 64-bit, depending on the system architecture.
Here's an example of how to declare and use integer types in Go:
package main
import "fmt"
func main() {
var a int8 = 127
var b int16 = 32767
var c int32 = 2147483647
var d int64 = 9223372036854775807
fmt.Println("a:", a)
fmt.Println("b:", b)
fmt.Println("c:", c)
fmt.Println("d:", d)
}
This code will output:
a: 127
b: 32767
c: 2147483647
d: 9223372036854775807
Go Floating-Point Types
Go also provides two floating-point types: float32
and float64
. These types are used to represent decimal numbers.
Here's an example of how to declare and use floating-point types in Go:
package main
import "fmt"
func main() {
var a float32 = 3.14
var b float64 = 3.14159265358979
fmt.Println("a:", a)
fmt.Println("b:", b)
}
This code will output:
a: 3.14
b: 3.14159265358979
Type Declaration and Inference
In Go, you can declare variables with or without explicitly specifying the type. When you don't specify the type, Go will infer it based on the value assigned to the variable.
Here's an example:
package main
import "fmt"
func main() {
var a = 42 // a is inferred to be an int
var b = 3.14 // b is inferred to be a float64
c := "hello" // c is inferred to be a string
d := 42.0 // d is inferred to be a float64
fmt.Println("a:", a)
fmt.Println("b:", b)
fmt.Println("c:", c)
fmt.Println("d:", d)
}
This code will output:
a: 42
b: 3.14
c: hello
d: 42