Conteúdo do Curso
Introduction to GoLang
Introduction to GoLang
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
):
index
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:
index
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:
index
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
:
index
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:
index
package main import "fmt" func main() { var text string = "a"; fmt.Printf(rune(text)) // Error here }
Obrigado pelo seu feedback!