【问题标题】:How to convert "uint" type into "string" type in Golang?如何在 Golang 中将“uint”类型转换为“string”类型?
【发布时间】:2019-12-02 21:37:22
【问题描述】:

我正在编写一段返回 uint 数据类型的代码。我需要将 uint 数据类型转换为字符串以便进一步处理。

我已经尝试过 strconv 包,但没有一个函数接受 uint。 Golang 文档:https://golang.org/ref/spec#Numeric_types 声明 uint 依赖于平台。这就是我们没有任何标准转换函数的原因吗?

type Example{
    Id uint    //value 3
    name string
}

需要将Id提取成字符串。

预期:“3” 实际:不适用

【问题讨论】:

    标签: go


    【解决方案1】:

    使用strconv.FormatUint():

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        var n uint = 123
        var s string = strconv.FormatUint(uint64(n), 10)
        fmt.Printf("s=%s\n", s)
    }
    

    (Go Playground)

    【讨论】:

    • 嗯.. 这不正确。我尝试过这个。它给出“不能使用 Example.Id 类型 uint 作为类型 uint64
    • @KaushalShah 是我的错,您需要将其显式转换为 uint64
    • 无论架构如何,所有内置类型都必须可用。
    • uint64 类型在所有架构上都可用,并且保证其大小大于或等于 uint 类型。该代码在所有架构上的工作方式都相同。
    • 没有。数学就是数学。如果它给出不同的答案,它就会从根本上被打破。
    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 2016-03-20
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2021-12-07
    相关资源
    最近更新 更多