What is type FloatType in Golang?
The FloatType identifier in Golang serves as a stand-in for either in-built float data type float32 or float64. Both the float32 and float64 data types represent numbers with decimal components.
The float32 data type occupies bits in memory, whereas the float64 data type occupies bits in memory. The default type for floating-point numbers is float64.
The command below shows how to declare a floating-point number in Golang:
var a float32 = 2.25
var b float64 = 2.50
var c = 3.20
In the code above, a is of type float32, whereas both b and c are float64.
Operators
Golang provides several operators for float data types:
- Arithmetic Operators:
+,-,*,/ - Comparison Operators:
==,!=,<,>,<=,>=
Type definition
Golang allows for new types to be defined using the in-built float data types, as shown below:
type FloatType float32
The FloatType keyword in the above example serves as a placeholder. You can choose any name for the new type identifier.
The command above declares a new type, myNewFloat, with the same properties as the float32 data type. The new type now serves as an identifier for declaring floating-point variables, as shown below:
var FloatType myNewFloat = 2.22
Function parameters and return types
The FloatType identifier is used in function prototypes to indicate that a floating-point type is to be provided or returned, as shown below:
func myFunc(a FloatType) FloatType
In the code above, the keyword FloatType alerts the compiler that either a float32 or float64 value must be provided as an argument to the function myFunc. That myFunc returns a floating-point value.
Example
The code below shows how float data types work in Golang:
package mainimport ("fmt")// new type declarationtype myNewFloat float32func main() {// initializing variablesvar a = 4.5var b float64 = 5.5var c myNewFloat = 6.5var d myNewFloat = 7.5// performing operationsfmt.Println(a + b)fmt.Println(a * b)fmt.Println(d - c)fmt.Println(d / c)}
Explanation
First, the type identifier declares a new float-type identifier on line with the properties of the float32 data type. This new type identifier is used to initialize two floating-point variables: c and d.
Two additional floating-point variables, a and b, are also initialized. Both of these variables are of the float64 type. a is declared without an explicit type identifier, so by default, Golang assigns it as a float64 type.
Lines involve arithmetic operations between variables of the same type. The fmt.Println function outputs the result of the operations.
Free Resources