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 3232 bits in memory, whereas the float64 data type occupies 6464 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 main
import (
"fmt"
)
// new type declaration
type myNewFloat float32
func main() {
// initializing variables
var a = 4.5
var b float64 = 5.5
var c myNewFloat = 6.5
var d myNewFloat = 7.5
// performing operations
fmt.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 88 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 202420-24 involve arithmetic operations between variables of the same type. The fmt.Println function outputs the result of the operations.

Copyright ©2024 Educative, Inc. All rights reserved