Go Type Casting
Type casting is used to convert a variable of one data type to another.
The basic format for type casting in Go is:
type_name(expression)
type_name is the type, and expression is the expression.
### Numeric Type Conversion
Converting an integer to a floating-point type:
var a int=10
var b float64=float64(a)
In the following example, an integer is converted to a floating-point type, the result is calculated, and the result is assigned to a floating-point variable:
## Example
package main
import"fmt"
func main(){
var sum int=17
var count int=5
var mean float32
mean =float32(sum)/float32(count)
fmt.Printf("mean value is: %fn",mean)
}
The output of the above example is:
mean value is: 3.400000
### String Type Conversion
To convert a string to another type, you can use the following syntax:
var str string = "10"var num int num, _ = strconv.Atoi(str)
The above code converts the string variable `str` to an integer variable `num`.
Note that the `strconv.Atoi` function returns two values: the first is the converted integer value, and the second is a possible error. We can use the blank identifier `_` to ignore this error.
The following example converts a string to an integer:
## Example
package main
import(
"fmt"
"strconv"
)
func main(){
str :="123"
num, err := strconv.Atoi(str)
if err !=nil{
fmt.Println("Conversion error:", err)
}else{
fmt.Printf("Strings '%s' Type cast to Integer:%dn", str, num)
}
}
The output of the above example is:
Strings '123' Type cast to Integer:123
The following example converts an integer to a string:
## Example
package main
import(
"fmt"
"strconv"
)
func main(){
num :=123
str := strconv.Itoa(num)
fmt.Printf("Integer %d Type cast to Strings:'%s'n", num, str)
}
The output of the above example is:
Integer 123 Type cast to Strings:'123'
The following example converts a string to a floating-point number:
## Example
package main
import(
"fmt"
"strconv"
)
func main(){
str :="3.14"
num, err := strconv.ParseFloat(str,64)
if err !=nil{
fmt.Println("Conversion error:", err)
}else{
fmt.Printf("Strings '%s' Converted to float:%fn", str, num)
}
}
The output of the above example is:
Strings '3.14' Converted to float: 3.140000
The following example converts a floating-point number to a string:
## Example
package main
import(
"fmt"
"strconv"
)
func main(){
num :=3.14
str := strconv.FormatFloat(num,'f',2,64)
fmt.Printf("Floating-point number %f Type cast to Strings:'%s'n", num, str)
}
The output of the above example is:
Floating-point number 3.140000 Type cast to Strings:'3.14'
### Interface Type Conversion
There are two cases for interface type conversion: **type assertion** and **type conversion**.
### Type Assertion
Type assertion is used to convert an interface type to a specified type. Its syntax is:
value.(type) or value.(T)
Here, `value` is a variable of an interface type, and `type` or `T` is the type to convert to.
If the type assertion is successful, it returns the converted value and a boolean value indicating whether the conversion was successful.
## Example
package main
import"fmt"
func main(){
var i interface{}="Hello, World"
str, ok :=i.(string)
if ok {
fmt.Printf("'%s' is a stringn", str)
}else{
fmt.Println("conversion failed")
}
}
In the above example, we define an interface type variable `i` and assign it the string "Hello, World". Then, we use a type assertion to convert `i` to a string type and assign the converted value to the variable `str`. Finally, we use the `ok` variable to check if the type conversion was successful. If successful, we print the converted string; otherwise, we print a conversion failure message.
### Type Conversion
Type conversion is used to convert a value of one interface type to another interface type. Its syntax is:
T(value)
Here, `T` is the target interface type, and `value` is the value to convert.
In type conversion, we must ensure that the value to be converted and the target interface type are compatible; otherwise, the compiler will report an error.
## Example
package main
import"fmt"
// Define an interface Writer
type Writer interface{
Write([]byte)(int, error)
}
// Implement the Writer interface with the StringWriter struct
type StringWriter struct{
str string
}
// Implement the Write method
func(sw *StringWriter) Write(data []byte)(int, error){
sw.str +=string(data)
return len(data),nil
}
func main(){
// Create a StringWriter instance and assign it to a Writer interface variable
var w Writer =&StringWriter{}
// Convert the Writer interface type to the StringWriter type
sw := w.(*StringWriter)
// Modify the StringWriter's field
sw.str="Hello, World"
// Print the value of the StringWriter's field
fmt.Println(sw.str)
}
**Analysis:**
1. **Define the interface and struct**:
* The `Writer` interface defines the `Write` method.
* The `StringWriter` struct implements the `Write` method.
2. **Type Conversion**:
* Assign a `StringWriter` instance to the `Writer` interface variable `w`.
* Use `w.(*StringWriter)` to convert the `Writer` interface type to the `StringWriter` type.
3. **Access the field**:
* Modify the `str` field of the `StringWriter` and print its value.
### Empty Interface Type
The empty interface `interface{}` can hold a value of any type. In practical applications, the empty interface is often used to handle values of multiple types.
## Example
package main
import(
"fmt"
)
func printValue(v interface{}){
switch v := v.(type){
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
}
func main(){
printValue(42)
printValue("hello")
printValue(3.14)
}
In this example, the `printValue` function accepts a parameter of an empty interface type and uses type assertion and a type switch to handle different types.
YouTip