Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Basic Type Casting | Data Types
Introduction to GoLang
course content

Зміст курсу

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

Basic Type Casting

Typecasting is the process of converting data from one data type to another. However, it's important to note that it's not always possible to convert data from one data type to another. For example, we can convert a float to an int and vice versa. However, it wouldn't make sense to convert a string to an int, and thus it's not possible.

There are two types of type conversions or typecasting. One of them is Implicit Type Casting. Implicit type casting occurs when Go automatically converts one type to another when it's safe and unambiguous. For example, when we assign an integer value to a float variable, it is treated as a float automatically, as no data can be lost during the conversion (10 is the same as 10.0):

go

index

copy
1
var myFloat float32 = 10 // A valid statement

The other type of type casting is Explicit Type Casting, which occurs when the programmer explicitly converts data or expressions from one type to another. The syntax for explicit type casting is desiredType(expression), for example:

go

index

copy
12345678
package main import "fmt" func main() { var number1 float32 = 7.9 var number2 int = int(number1) fmt.Println(number2) // Outputs 7 }

In the above program, we convert a float32 value to an int using explicit type casting. As a result, the decimal part of the original number is discarded, and only the integral value 7 is stored in number2. It's important to note that in this case, some data is lost, specifically the decimal part of the number (0.9). However, we made that choice explicitly.

Similarly, we can convert a rune into a string. In the Runes chapter, we explored a program that outputted the value of a Rune, which was a number. However, we can display a Rune's character equivalent by converting it into a string:

go

index

copy
123456789
package main import "fmt" func main() { var char rune = 'a' fmt.Println(char) // Outputs 97 fmt.Println(string(char)) // Outputs 'a' }

However, we cannot convert a string into a rune:

go

index

copy
12
var myString string = "A string value" fmt.Println(rune(myString)) // Error: cannot convert myString (variable of type string) to type rune

It is important to note we can also not convert a string containing a single character into a rune:

go

index

copy
1234567
package main import "fmt" func main() { var text string = "a"; fmt.Printf(rune(text)) // Error here }

Which of the following is the correct syntax for type casting in Go?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 2. Розділ 6
We're sorry to hear that something went wrong. What happened?
some-alt