数据类型确定可以分配给该类型的值以及可以对其执行的操作。数据类型的转换是编程中广泛使用的操作,并且在数据类型转换中,从整型 int 到字符串值的转换非常流行。

strconv
intUTF-8
package main
import "fmt"
func main() {
    s := string(97)
    fmt.Printf("Value of 97 after conversion : %v\n", s)
}

输出:

Value of 97 after conversion : a

但这是不可取的,因此我们使用一些标准函数将整数转换为字符串数据类型,下面将对此进行讨论:

strconvItoa
strconvstrconvItoa
package main
import (
    "fmt"
    "strconv"
)
func main() {
    x := 138
    fmt.Printf("Datatype of 138 before conversion : %T\n", x)
    a := strconv.Itoa(x)
    fmt.Printf("Datatype of 138 after conversion : %T\n", a)
    fmt.Println("Number: " + a)
}

输出:

Datatype of 138 before conversion : int
Datatype of 138 after conversion : string
Number: 138
strconvFormatInt
strconv.FormatIntFormatInt2base36>= 10
package main
import (
    "fmt"
    "strconv"
)
func main() {
    var integer_1 int64 = 31
    fmt.Printf("Value of integer_1 before conversion : %v\n", integer_1)
    fmt.Printf("Datatype of integer_1 before conversion : %T\n", integer_1)
    var string_1 string = strconv.FormatInt(integer_1, 10)
    fmt.Printf("Value of integer_1 after conversion in base 10: %v\n", string_1)
    fmt.Printf("Datatype of integer_1 after conversion in base 10 : %T\n", string_1)
    var string_2 string = strconv.FormatInt(integer_1, 16)
    fmt.Printf("Value of integer_1 after conversion in base 16 : %v\n", string_2)
    fmt.Printf("Datatype of integer_1 after conversion in base 16 : %T\n", string_2)
}

输出:

Value of integer_1 before conversion : 31
Datatype of integer_1 before conversion : int64
Value of integer_1 after conversion in base 10: 31
Datatype of integer_1 after conversion in base 10 : string
Value of integer_1 after conversion in base 16 : 1f
Datatype of integer_1 after conversion in base 16 : string
fmt.Sprint
fmt.Sprint
package main
import (
    "fmt"
)
func main() {
    x := 138
    fmt.Printf("Datatype of 138 before conversion : %T\n", x)
    a := fmt.Sprint(x)
    fmt.Printf("Datatype of 138 after conversion : %T\n", a)
    fmt.Println("Number: " + a)
}

输出:

Datatype of 138 before conversion : int
Datatype of 138 after conversion : string
Number: 138
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。