Go language type conversion

Type conversion is used to convert a variable of one data type into a variable of another type.

The basic format of type conversion in Go is as follows:

type_name(expression)

type_name is the type, and expression is the expression.

Numeric type conversion

Convert integer to floating-point:

var a int = 10
var b float64 = float64(a)

In the following example, convert an integer to a floating-point type, calculate the result, and assign the result 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("The value of mean is: %f\n"\n",mean)
}

The output of the above example is:

mean 的值为: 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,strconv.AtoiThe 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("The string '%s' converted to integer is: %d\n"\n", str, num)
    }
}

The output of the above example is:

字符串 '123' 转换为整数为: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 converted to string is: '%s'"\n", num, str)
}

The output of the above example is:

整数 123  转换为字符串为:'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("The string '%s' converted to float is: %f"\n", str, num)
    }
}

The output of the above example is:

字符串 '3.14' 转为浮点型为: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(The float %f converted to a string is: '%s'\n", num, str)
}

The output of the above example is:

浮点数 3.140000 转为字符串为:'3.14'

Interface type conversion

There are two cases of interface type conversionType assertionandType conversion。

Type assertion

Type assertion is used to convert an interface type to a specified type. Its syntax is:

value.(type) 
或者 
value.(T)

Here, value is a variable of interface type, and type or T is the target type to convert to.

If the type assertion succeeds, it returns the converted value and a boolean value indicating whether the conversion succeeded.

Example

package main

import "fmt"

func main() {
    var i interface{} = "Hello, World"
    str, ok := i.(string)
    if ok {
        fmt.Printf("'%s' is a string\n", 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 the string type and assign the converted value to variable str. Finally, we use the ok variable to check whether the type conversion was successful. If successful, we print the converted string; otherwise, we print a message indicating that the conversion failed.

Type conversion

Type conversion is used to convert a value of an interface type to another interface type. Its syntax is:

T(value)

T is the target interface type, and value is the value to be converted.

In type conversion, we must ensure that the value to be converted is compatible with the target interface type; otherwise, the compiler will report an error.

Example

package main

import "fmt"

// Define a Writer interface
type Writer interface {
    Write([]byte) (int, error)
}

// The StringWriter struct implements the Writer interface
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 StringWriter type
    sw := w.(*StringWriter)
   
    // Modify StringWriter's field
    sw.str = "Hello, World"
   
    // Print StringWriter's field value
    fmt.Println(sw.str)
}

Analysis:

  1. Define interface and struct:

    • WriterThe interface definesWritemethod.
    • StringWriterThe struct implementsWritemethod.
  2. Type conversion:

    • willStringWriterassign the instance toWriterinterface variablew。
    • Usagew.(*StringWriter)willWriterInterface type converted toStringWritertype.
  3. access fields:

    • modifyStringWriterthe fieldstr, and print its value.

empty interface type

Empty interfaceinterface{}It can hold values 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 empty interface type and uses type assertion and type switch to handle different types.

other extensions