Welcome to our comprehensive guide on Go Type Conversion! In this lesson, we'll dive into the world of data types and conversion in Go, a powerful programming language known for its simplicity and efficiency. By the end of this tutorial, you'll be able to convert different data types with confidence, ready to tackle real-world projects. 💡
Before we delve into type conversion, let's briefly review the basic data types available in Go:
int (integer): whole numbers, e.g., 123 or -100float32 and float64 (floating-point): numbers with decimal points, e.g., 3.14 or -2.718bool (boolean): true or false valuesstring: sequences of characters, e.g., "Hello, World!"Type conversion in Go can be implicit (automatic) or explicit (using conversion functions). Let's explore both methods.
Implicit type conversions happen automatically when we assign a value of one data type to a variable of another data type, without using a conversion function. Go performs the conversion based on the rules of type promotion.
Here's an example of implicit type conversion:
package main
import "fmt"
func main() {
var a int = 42
var b float64 = float64(a) // implicit conversion from int to float64
fmt.Printf("a: %T, b: %T\n", a, b)
fmt.Println("a: ", a, ", b: ", b)
}Output:
a: int, b: float64
a: 42, b: 42
In this example, we assigned an integer value to a float64 variable, resulting in an implicit conversion.
Explicit type conversions are achieved using conversion functions. The most common conversion functions are float64(), int(), and uintptr().
Here's an example of explicit type conversion:
package main
import "fmt"
func main() {
var b float64 = 3.14
var a int = int(b) // explicit conversion from float64 to int
fmt.Printf("b: %T, a: %T\n", b, a)
fmt.Println("b: ", b, ", a: ", a)
}Output:
b: float64, a: int
b: 3.14, a: 3
In this example, we converted a float64 value to an int using the int() conversion function.
:::quiz Question: What is the output of the following code snippet?
package main
import "fmt"
func main() {
var a float64 = 3.14
var b int = int(a)
fmt.Printf("a: %T, b: %T\n", a, b)
fmt.Println("a: ", a, ", b: ", b)
}A: a: float64, b: float64 and a: 3.14, b: 3.14
B: a: float64, b: int and a: 3.14, b: 3
C: a: int, b: float64 and a: 3, b: 3.14
Correct: B
Explanation: In this code snippet, we're converting a float64 value to an int. The output will show a as float64 and b as int, with the decimal part being truncated.