ADVERTISEMENT
ADVERTISEMENT

Type Casting or Type Conversion in Golang

Golang | Type Casting or Type Conversion: In this tutorial, we are going to learn about type casting or type conversion with examples in Go language.
Submitted by IncludeHelp, on August 30, 2021

Prerequisites:

In computer science, the type conversion or typecasting is used to change an entity of one data type into another. There are two types of type conversion: implicit type conversion and explicit type conversion. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting.

Statically typed languages like C, C++, Java provide the feature of implicit type conversion. Many times (if datatypes are compatible) there is no need to convert a type to another, it happens automatically. But Go language does not support the implicit type conversion even if the datatypes are compatible. This is because of the Strong Type System provided by the Go language. Whenever we need to convert a type to another – we use explicit type conversion in the Go language.

Note: In the Go language, there is no typecasting terminology. There is only Type Conversion. In Other programming languages, typecasting is also termed as the "type conversion".

Explicit Type Conversion

To convert a data type to another in Golang – The expression T(v) converts the value v to the type T. The system for explicit type conversion is,

T(v)

Here,

  • T is the targeted Type.
  • v is the value/ variable to be converted to the T type.

Example:

(float64)42

Example 1:

// Golang program to demonstrate the
// concept of type conversion

package main

import (
	"fmt"
)

func main() {
	var x int = 42
	// converting int to float64
	var y float64 = float64(x)
	// converting float64 to uint
	var z uint = uint(y)

	// printing the types and values of the variables
	fmt.Printf("Value of x is %d and type is %T\n", x, x)
	fmt.Printf("Value of y is %.2f and type is %T\n", y, y)
	fmt.Printf("Value of z is %d and type is %T\n", z, z)
}

Output:

Value of x is 42 and type is int
Value of y is 42.00 and type is float64
Value of z is 42 and type is uint

Example 2:

// Golang program to demonstrate the
// concept of type conversion
// Find the average of two integer numbers

package main

import (
	"fmt"
)

func main() {
	// Declare the variables
	var num1 int
	var num2 int
	var avg float64

	// Assign the values
	num1 = 10
	num2 = 5

	// Calculate the average
	// Here, we will use the
	// explicit type conversion
	avg = (float64(num1) + float64(num2)) / 2

	// Print the values
	fmt.Printf("Average of %d and %d is %.2f\n", num1, num2, avg)
}

Output:

Average of 10 and 5 is 7.50

If we don't use the explicit type conversion, the program will generate an error. In the above program, remove the type conversion,

avg = (num1 + num2) / 2

And, run the program – you will find the following error,

cannot use (num1 + num2) / 2 (type int) as type float64 in assignment

Because the variables num1 and num2 are as integer (int) types and avg is float64 types. The result will not be assigned to the variables avg if types of num1 and num2 are not changed.

Example 3: When types are compatible

In the C programming language – a positive integer value (int) can be assigned in an unsigned integer (unsigned int or uint) automatically (implicit type conversion). But in the Go language, this assignment will not happen.

See the below examples (C language code & Go language code) demonstrating the concept of implicit type conversation.

C code:

#include <stdio.h>

int main()
{
    int a = 123;
    unsigned int b =0;
    
    // Assign the value of a to the b
    b =a;
    
    // Printing the both values
    printf("a = %d, b = %u\n",a,b);

    return 0;
}

Output:

a = 123, b = 123

Go code:

package main

import (
	"fmt"
)

func main() {
	var a int = 123
	var b uint = 0

	// Assign the value of a to the b
	b = a

	// Printing the both values
	fmt.Printf("a = %d, b = %d\n", a, b)
}

Output:

cannot use a (type int) as type uint in assignment

As explained, the Go language doesn't support the implicit type conversion even if the types are compatible. To fix the above error, we have to use explicit type conversion (b = uint(a)).

Correct Go code:

package main

import (
	"fmt"
)

func main() {
	var a int = 123
	var b uint = 0

	// Assign the value of a to the b
	b = uint(a)

	// Printing the both values
	fmt.Printf("a = %d, b = %d\n", a, b)
}

Output:

a = 123, b = 123

Example 4:

// Golang program to demonstrate the
// concept of type conversion
// Find the square root of a number

package main

import (
	"fmt"
	"math"
)

func main() {
	var x int = 225
	var SqrtX float64

	// Find the square root
	SqrtX = math.Sqrt(float64(x))

	// Print the values
	fmt.Printf("Square root of %d is %.2f\n", x, SqrtX)
}

Output:

Square root of 225 is 15.00

In the above program, we also convert the x from int type to the float64 type, because the math.Sqrt() function accepts the float64 type value.


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.