Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language Type Conversion

Go Language Type Conversion

Type conversion is used to convert a variable of one data type into another data 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

Converting an integer to a floating-point type:

var

a

int

=

10

var

b

float64

=

float64

(

a

)

The following example converts an integer to a floating-point number, computes the result, and assigns 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"

,

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 code above converts the string variable str to the 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

(

"The string '%s' converted to an integer is: %d\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

(

"The integer %d \u00a0converted to a 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 a floating-point number 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 floating-point number %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 conversion**: type assertionandand type conversion**.

Type assertions

A type assertion is used to convert an interface type to a specified type; its syntax is:



value.(type) 

或者 

value.(T)

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

If the type assertion succeeds, 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 string\n"

,

str

)

   

}

else

{

        fmt

.

Println

(

"conversion failed"

)

   

}

}

In the example above, we define a variable i of interface type 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 whether the type conversion succeeded; if it succeeds, we print the converted string; otherwise, we print a 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)

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

In a 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 an interface Writer

type

Writer

interface

{

    Write

([]

byte

)

(

int

,

error

)

}

// the struct StringWriter that 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 the StringWriter type

    sw

:=

w

.

(

StringWriter

)

   

   

// modify the field of StringWriter

    sw

.

str

=

"Hello, World"

   

   

// print the field value of StringWriter

    fmt

.

Println

(

sw

.

str

)

}

Analysis:

  1. Defining Interfaces and Structs:

  2. Writer The interface defines Write method.
  3. StringWriter struct implements Write method.
  4. - The `Writer` interface defines the `Write` method. - The `StringWriter` struct implements the `Write` method.
    1. Type Conversion:

    2. data to the child component via StringWriter instance to Writer Interface Variable w。
    3. Use w.(*StringWriter) data to the child component via Writer Interface type conversion to StringWriter type.
    4. - Assign a `StringWriter` instance to the `Writer` interface variable `w`. - Use `w.(*StringWriter)` to convert the `Writer` interface type to the `StringWriter` type.
      1. Access a field:

      2. Modify StringWriter the field str, and print its value.
      3. - Modify the `str` field of `StringWriter` and print its value.

        Empty Interface Type

        The empty interface interface{} can hold values of any type. In practice, empty interfaces are 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 assertions and type switches to handle different types.